是否将参数副本或参数本身传递给__init__中的函数? [英] Do I pass copies of arguments or the arguments themselves to functions within __init__?
问题描述
我想知道以下两种选择中的哪一种更好,或者也许更适合Pythonic:
I would like to know which one of the following two alternatives is better, or maybe more Pythonic:
-
直接将
__ init __
参数用作__ init __
中调用的函数的参数:
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:
-
由于很多
self.
键入避免了冗长的代码,并且代码更具可读性.
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
是属性,它在设置或获取时会以某种方式转换值,那么您就别无选择,取决于您是否需要使用原始的 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屋!