我正在尝试了解如何在python中使用mixins。我想让鸟、狗和蝙蝠类具有PetMixIn
类中的eat
方法,但也可以是自我实例。我应该怎么做?
class Pet(object):
def __init__(self, food):
self.food = food
def eat(self):
print(f'Eatting...{self.food}')
class PetMixIn(object):
def eat(self):
print('Eatting...')
class Animal(object):
def __init__(self, life):
self.liferange = life
class Bird(Animal):
def __init__(self, life, flyable):
super.__init__(lift)
self.flyable = flyable
#bird attribution ...
class Dog(Animal):
def __init__(self, life, name):
super.__init__(lift)
self.name = name
#dog attribution ...
class Bat(Animal):
def __init__(self, life, size):
super.__init__(lift)
self.size = size
#bat attribution ...
bat = Bat(40, '1')
dog = Dog(10, 'tom')
bird = Bird(3, True)
这里有一个小例子(python3(
class PetMixIn:
xxx = 2
def eat(self):
print('Eatting...')
class Animal:
def __init__(self, life):
self.liferange = life
class Bat(Animal, PetMixIn):
def __init__(self, life, size):
super().__init__(life)
self.size = size
#bat attribution ...
bat = Bat(40, '1')
bat.eat()
print(bat.xxx)