Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python classes #4

Open
olliesilvester opened this issue Jul 8, 2024 · 1 comment
Open

Python classes #4

olliesilvester opened this issue Jul 8, 2024 · 1 comment

Comments

@olliesilvester
Copy link
Owner

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants