Or can they be declared otherwise?
The code below does not work:
class BinaryNode():
self.parent = None
self.left_child = None
Do they need to be declared in __init__
?
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.
However,
class BinaryNode():
parent = None
left_child = None
def run(self):
self.parent = "Foo"
print self.parent
print self.left_child
The output will be
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)
Nope. I love the @property
variable for just this thing:
class Data(object):
"""give me some data, and I'll give you more"""
def __init__(self, some, others):
self.some = some
self.others = others
@property
def more(self):
"""you don't instantiate this with __init__, per say..."""
return zip(self.some, self.others)
>>> mydata = Data([1, 2, 3], ['a', 'b', 'c'])
>>> mydata.more
[(1, 'a'), (2, 'b'), (3, 'c')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With