Must all Python instance variables be declared in def __init__?

后端 未结 4 2130
挽巷
挽巷 2021-01-02 05:36

Or can they be declared otherwise?

The code below does not work:

class BinaryNode():
    self.parent = None
    self.left_child = None
4条回答
  •  無奈伤痛
    2021-01-02 05:50

    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')]
    

提交回复
热议问题