Python使用子类中父类的变量

时间:2016-12-19 17:22:09

标签: python

您如何能够在子类的方法中从父类访问变量?

例如,像这样:

{{1}}

感谢。

2 个答案:

答案 0 :(得分:4)

首先:要实际初始化您需要确保Parent.__init__实际运行所需的变量,例如不要覆盖__init__,然后只需将其作为self.y访问:

class Parent:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Child(Parent):

    def firstMethod(self):
        print(self.y)

另一种可能性是致电父母__init__,但仍然可以通过self.y访问它:

class Parent:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Child(Parent):
    def __init__(self, x, y):
        super().__init__(x, y)
        # additional processing

    def firstMethod(self):
        print(self.y)

答案 1 :(得分:-1)

class Parent:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Child(Parent):
    def __init__(self, x, y):
        # initialize Parent with your needed data           
        Parent.__init__(self, x,y)
        # or call mata class
        # super().__init__(x,y)

    def firstMethod(self):
        print(self.y) # or something?

c = Child(20,20)
c.firstMethod()
# 20