1

I am trying to understand how to use mixins in python. I want to make Bird, Dog and Bat class to have the eat method from PetMixIn class but also can be self instance. How should I do it?

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)
quamrana
  • 37,849
  • 12
  • 53
  • 71
jacobcan118
  • 7,797
  • 12
  • 50
  • 95

1 Answers1

2

Here a small example (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)
djangoliv
  • 1,698
  • 14
  • 26
  • what if I have some attribution in PetMixIn need to use? like *self.xxx*? – jacobcan118 Apr 05 '18 at 15:45
  • not sure to understand. You want an __init__ in your mixin ? – djangoliv Apr 05 '18 at 16:07
  • The `PetMixIn` class has the method `def eat(self):`. And there it is: `self` in the method signature. Any method you define on the mixin can use `self` any way an `Animal` would, even though there is no inheritance connection. Python is a dynamic language after all. – quamrana Apr 06 '18 at 07:44