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)
答案 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