Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must all Python instance variables be declared in def __init__?

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__?

like image 876
aerain Avatar asked Sep 05 '12 03:09

aerain


2 Answers

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)
like image 114
sberry Avatar answered Oct 16 '22 05:10

sberry


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')]
like image 43
yurisich Avatar answered Oct 16 '22 05:10

yurisich