首先,我知道有一种正确的方法可以实现如下继承:
class Parent():
def __init__(self, last_name, eye_color):
self.last_name = last_name
self.eye_color = eye_color
class Child(Parent):
def __init__(self, last_name, eye_color, number_of_toys):
Parent.__init__(self, last_name, eye_color)
self.number_of_toys = number_of_toys
miley_cyrus = Child("Cyrus", "Blue", 5)
print(miley_cyrus.last_name)
print(miley_cyrus.number_of_toys)
当我运行这段代码时,结果是
Cyrus
5
但是当我把第7行改成:
self = Parent(last_name, eye_color)
代码变成了:
class Parent():
def __init__(self, last_name, eye_color):
self.last_name = last_name
self.eye_color = eye_color
class Child(Parent):
def __init__(self, last_name, eye_color, number_of_toys):
self = Parent(last_name, eye_color)
self.number_of_toys = number_of_toys
miley_cyrus = Child("Cyrus", "Blue", 5)
print(miley_cyrus.last_name)
print(miley_cyrus.number_of_toys)
,我运行这段代码,有一个错误表明:
Traceback (most recent call last):
File "/Users/Echo/Documents/IT/Udacity/python/7.Inheritance/inherentance.py", line 12, in <module>
print(miley_cyrus.last_name)
AttributeError: Child instance has no attribute 'last_name'
怎么了?提前谢谢。你知道吗
我不知道你在做什么,但你可以通过这种方式得到预期的结果。你知道吗
self = Parent
应该是self.some_variable = Parent
我认为这一点的答案并没有真正触及实际问题。在我的解释中,你认为
self
是一种可以手动更改的上下文。你知道吗您是否知道
self
确实是您正在创建的实例?重新分配它不仅会让人困惑,而且会是错误的——即使分配给参数是不可能的。你知道吗您可以执行这段代码,它显示您正试图将
miley_cyrus
变异为Parent
初始值设定项内部的Child
:另外,我认为术语初始值设定项在这里非常重要,因为你可能会与传统语言混淆。Python有一个单独的magic方法,负责实际创建对象(
__new__
)。在调用__init__
时,您已经在实例化对象上操作了。这就是__new__
接受类对象而不是self
的原因。你知道吗相关问题 更多 >
编程相关推荐