是否必须在def __init__中声明所有Python实例变量?
还是可以用其他方式声明它们?
Or can they be declared otherwise?
下面的代码不起作用:
class BinaryNode():
self.parent = None
self.left_child = None
是否需要在__init__
中声明它们?
Do they need to be declared in __init__
?
不必在__init__
中声明它们,但是为了使用self
设置实例变量,需要引用self
,而您定义变量的位置则没有.
They do not have to be declared in __init__
, but in order to set an instance variable using self
, there needs to be a reference to self
, and the place you are defining the variables does not.
但是,
class BinaryNode():
parent = None
left_child = None
def run(self):
self.parent = "Foo"
print self.parent
print self.left_child
输出将为
Foo
None
要在评论中回答您的问题,是的.在我的示例中,您可以说:
To answer your question in the comment, yes. You can, in my example say:
bn = BinaryNode()
bn.new_variable = "Bar"
或者,正如我所展示的,您可以设置一个类级别的变量.该类的所有新实例将在实例化时获得类级别变量的副本.
Or, as I showed, you can set a class level variable. All new instances of the class will get a copy of the class level variables at instantiation.
也许您不知道可以将参数传递给构造函数:
Perhaps you are not aware that you can pass arguments to the constructor:
class BinaryNode(object):
def __init__(self, parent=None, left_child=None):
self.parent = parent
self.left_child = left_child
bn = BinaryNode(node_parent, node_to_the_left)