gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:22 26 4
gpt4 key购买 nike

<分区>

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

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'

这有什么问题?提前致谢。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com