为什么我不能像这样实现继承?

2024-06-01 02:14:31 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我知道有一种正确的方法可以实现如下继承:

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'

怎么了?提前谢谢。你知道吗


Tags: ofnameselfchildnumberinitclasscolor
2条回答

我不知道你在做什么,但你可以通过这种方式得到预期的结果。你知道吗

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.obj = Parent(last_name, eye_color)
        self.number_of_toys = number_of_toys

miley_cyrus = Child("Cyrus", "Blue", 5)
print(miley_cyrus.obj.last_name)
print(miley_cyrus.number_of_toys)

self = Parent应该是self.some_variable = Parent

我认为这一点的答案并没有真正触及实际问题。在我的解释中,你认为self是一种可以手动更改的上下文。你知道吗

您是否知道self确实是您正在创建的实例?重新分配它不仅会让人困惑,而且会是错误的——即使分配给参数是不可能的。你知道吗

您可以执行这段代码,它显示您正试图将miley_cyrus变异为Parent初始值设定项内部的Child

class Parent(object):
    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):
        # hex(id(self)) -> 0x7fe2325a7da0
        self.number_of_toys = number_of_toys

miley_cyrus = Child("Cyrus", "Blue", 5) # hex(id(miley_cyrus)) -> 0x7fe2325a7da0

另外,我认为术语初始值设定项在这里非常重要,因为你可能会与传统语言混淆。Python有一个单独的magic方法,负责实际创建对象(__new__)。在调用__init__时,您已经在实例化对象上操作了。这就是__new__接受类对象而不是self的原因。你知道吗

相关问题 更多 >