python中的属性错误,对象没有属性

e1xvtsh3  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(140)

我对类中的继承不熟悉,由于某种原因,这段代码中的属性似乎没有正确共享。我不确定是什么问题。

class Person:
    def __init__(self, name, age, occupation):
      self.name = name
      self.age = age
      self.occupation = occupation
  
    def say_hello(self):
      print(f"Hello, my name is {self.name}.")
  
    def say_age(self):
      print(f"I am {self.age} years old.")
    
class Superhero(Person):
    def __init__(self, name, age, occupation, secret_identity, nemesis):
      self.secret_identity = secret_identity
      self.nemesis = nemesis

hero = Superhero("Spider-Man", 17, "student", "Peter Parker", "Green Goblin")
print(hero.name())
z9smfwbn

z9smfwbn1#

看起来您没有在Superhero类中调用super构造函数。您应该执行以下操作:

class Superhero(Person):
    def __init__(self, name, age, occupation, secret_identity, nemesis):
      super().__init__(name, age, occupation)
      self.secret_identity = secret_identity
      self.nemesis = nemesis

顺便说一句:你没有定义一个名为name的函数。如果你想打印名称,你应该删除(),例如print(hero.name)

相关问题