在另一个python类中使用实例属性

时间:2018-08-27 23:48:02

标签: python

class User:
    def __init__(self, name, age, country, title, ph):
        self.name = name
        self.age = age
        self.country = country
        self.title = title
        self.ph = ph



class Programmer(User):
    def __init__(self, address):
        self.address=address

    def do_something(self):
        print self.name
        print self.age
        print self.title
        print self.country + " " + self.ph


brian = User("brian", "28", "US", "Mr", "123556")

diana = Programmer("newark", brian)
diana.do_something()

错误:

Traceback (most recent call last):
  File "C:/Users/esurega/Desktop/NPI_TA/enm2enm/test/test.py", line 24, in <module>
    diana = Programmer("newark", brian)
TypeError: __init__() takes exactly 2 arguments (3 given)

1 个答案:

答案 0 :(得分:0)

即使您的Programmer类继承了__init__,也不会在User方法中初始化其父类的任何属性。

您可以使Programmer.__init__使用User对象初始化父类:

class Programmer(User):
    def __init__(self, address, user):
        super(Programmer, self).__init__(user.name, user.age, user.country, user.title, user.ph)
        self.address=address

或仅在user中创建一个Programmer属性以引用其基于的User,而不是使Programmer类继承User:< / p>

class Programmer:
    def __init__(self, address, user):
        self.user = user
        self.address = address

    def do_something(self):
        print self.user.name
        print self.user.age
        print self.user.title
        print self.user.country + " " + self.user.ph