gpt4 book ai didi

python - 如何使用mixin类为python中的多个类提供方法

转载 作者:行者123 更新时间:2023-12-01 02:00:46 27 4
gpt4 key购买 nike

我试图了解如何在 python 中使用 mixin。我想让 Bird、Dog 和 Bat 类拥有 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)

关于python - 如何使用mixin类为python中的多个类提供方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49674272/

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