代码之家  ›  专栏  ›  技术社区  ›  Lokesh Agrawal

如何在Python中创建父类的对象[[副本]

  •  0
  • Lokesh Agrawal  · 技术社区  · 7 年前

    我不确定在Python中如何创建父类的对象。考虑以下场景。

    class Animal():
        def __init__(self):
            print("Animal is created")
    
        def eat(self):
            print("I am eating")
    
    class Dog(Animal):
    
        def __init__(self, breed, name, spots):
            self.breed = breed
            self.name = name
            self.spots = spots
    
        def bark(self):
            print("Woof! My name is {}".format(self.name))
    
    my_dog = Dog(breed="lab", name="Sam", spots=False)
    

    这不打印“动物是被创造的”。

    class Animal():
        def __init__(self):
            print("Animal is created")
    
        def eat(self):
            print("I am eating")
    
    class Dog(Animal):
    
        def __init__(self, breed, name, spots):
            Animal.__init__(self)
            self.breed = breed
            self.name = name
            self.spots = spots
    
        def bark(self):
            print("Woof! My name is {}".format(self.name))
    
    my_dog = Dog(breed="lab", name="Sam", spots=False)
    

    而这张照片上写着“动物是被创造的”

    但在这两种情况下,我都可以从Dogs实例(my\u dog)访问Animal类的eat()方法。这意味着动物在这两种情况下都是被创造出来的。那为什么我看不到在第一种情况下动物会被召唤?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alex    7 年前

    你应该调用父类( Animal __init__ 中的方法 Dog __初始化__ super . 这被认为是比 Dog.__init__ 因为它不显式要求父类的名称。

    class Dog(Animal):
    
        def __init__(self, breed, name, spots):
            super().__init__()
            self.breed = breed
            self.name = name
            self.spots = spots