我试图了解如何在python中使用mixins。我想让Bird,Dog和Bat类具有来自eat
类的PetMixIn
方法,但也可以是自我实例。我该怎么办?
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)
答案 0 :(得分:2)
这是一个小例子(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)