我是否将参数的副本或参数本身传递给 __init__ 中的函数? [英] Do I pass copies of arguments or the arguments themselves to functions within __init__?

查看:19
本文介绍了我是否将参数的副本或参数本身传递给 __init__ 中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下两种选择中哪一种更好,或者更像 Pythonic:

I would like to know which one of the following two alternatives is better, or maybe more Pythonic:

  1. 直接使用 __init__ 参数作为 __init__ 中调用的函数的参数:

  1. Use __init__ arguments directly as arguments of functions called within __init__:

def class A(object):
    def __init__(self, x):
        self.x = x # I would like to do this anyway
        self.y = foo(x)
        # More code

  • 使用作为参数副本的 __init__ 属性作为在 __init__ 中调用的函数的参数:

  • Use __init__ attributes that are copies of arguments as arguments of functions called within __init__:

    def class B(object):
        def __init__(self, x):
            self.x = x # I would like to do this anyway
            self.y = foo(self.x)
            # More code
    

  • A 类和 B 类的行为应该相同.然而:

    The classes A and B should behave identically. However:

    1. 第一种选择不那么冗长,因为避免了很多 self. 输入并且代码更具可读性.

    1. The first alternative is less verbose since a lot of self. typing is avoided and the code is more readable.

    第二种选择可能对代码的进一步更改更加稳健.

    The second alternative may be more robust to further changes in the code.

    A 和 B 哪个更好?或者也许这无关紧要?

    Which one of A or B is better? Or perhaps it does not matter?

    推荐答案

    这无关紧要.不必输入 self 很好,而且 Python 不必进行属性查找.

    It matters very little. Not having to type out self is nice, and Python won't have to do an attribute lookup.

    然而,如果 self.x 是一个 property 在设置或获取时以某种方式转换值,那么你别无选择,这取决于你是否需要使用原始的x 或转换后的self.x.

    However, if self.x is a property that in some way transforms the value when setting or getting, then you have no choice, depending on wether or not you need to use the original x or the transformed self.x.

    这篇关于我是否将参数的副本或参数本身传递给 __init__ 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆