Python: Getting baseclass values from derived class

前端 未结 2 1419
离开以前
离开以前 2021-01-11 15:01

Hope this is clear enough:

class myParent():
    def __init__( self ):
        self.parentNumber = 5

class Child( myParent ):
    def __init__( self ):
             


        
2条回答
  •  轮回少年
    2021-01-11 15:31

    You just need to tell Child to run the initialization from myParent. After that, the current instance (self) has all the instance attributes an instance of myParent would have ("is a"), so you can use self.parentNumber. You do so by putting super(Child, self).__init__() into Child.__init__ (ideally, on the very first line) - myParent.__init__(self) would work, but it can be wrong (in subtle way) when the base class changes or in case of multiple inheritance. You can drop all the arguments to super if you're using Python 3.

    Also note that

    class C(object):
        x = ...
    

    is very different from

    class C(object):
        def __init__(self):
            self.x = ...
    

    The former creates a class variable, which is shared by all instances of C. The latter create an instance variable, each instance of C has it's own. (Likewise, global variables aren't bound to instances - but I assume you were talking about the above?)

提交回复
热议问题