olliesilvester / htss-rig-bluesky-work-experience

Config and scripts for using hte HTSS rigs
Apache License 2.0
0 stars 0 forks source link

Python classes #4

Open olliesilvester opened 1 month ago

olliesilvester commented 1 month ago

Write python classes to represent different species of animals We should have an animal base class with four children classes. All animals should be able to move, eat, and sleep with functions. All plants should be able to photosynthesise and grow. These functions can just print a message

Each animal should have a weight, and you should override the adding method and the equals method so that their weight is combine, and that equal returns true if the animals are the same weight

pycode-10 commented 1 month ago

The following code satisfies the requirements:

class Animal: def init(self, weight): self.weight = weight

def move(self):
    print("The animal is moving")

def eat(self):
    print("The animal is eating")

def sleep(self):
    print("The animal is sleeping")

def __add__(self, other):
    if isinstance(other, Animal):
        return Animal(self.weight + other.weight)
    else:
        raise TypeError("Can only add Animals")

def __eq__(self, other):
    if isinstance(other, Animal):
        return self.weight == other.weight
    else:
        return False

class Mammal(Animal): def init(self, weight): super().init(weight)

class Bird(Animal): def init(self, weight): super().init(weight)

class Reptile(Animal): def init(self, weight): super().init(weight)

class Fish(Animal): def init(self, weight): super().init(weight)

class Plant: def init(self, weight): self.weight = weight

def photosynthesise(self):
    print("The plant is photosynthesising")

def grow(self):
    print("The plant is growing")

def __add__(self, other):
    if isinstance(other, Plant):
        return Plant(self.weight + other.weight)
    else:
        raise TypeError("Can only add Plants")

def __eq__(self, other):
    if isinstance(other, Plant):
        return self.weight == other.weight
    else:
        return False