How would I make a function called nextyear() that increases all the animals age by 1?
class Animal:
def __init__(self, age):
self.age=age
animal1 = Animal (5)
animal2 = Animal (7)
animal3 = Animal (3)
you could use a class variable and a property:
class Animal:
year = 0
def __init__(self, age):
self._age = age - self.__class__.year
@property
def age(self):
return self._age + self.__class__.year
@classmethod
def next_year(cls):
cls.year += 1
animal1, animal2, animal3 = Animal(5), Animal(7), Animal(3)
for animal in (animal1, animal2, animal3):
print(animal.age)
print("Next year:")
Animal.next_year()
for animal in (animal1, animal2, animal3):
print(animal.age)
You would have to keep a list of the animals who are instances of the class, and add a class method to increase the age:
class Animal:
_animals = []
def __init__(self, age):
self.age = age
self._animals.append(self)
print(self._animals)
@classmethod
def one_year_more(cls):
for animal in cls._animals:
animal.age += 1
def __str__(self):
return "I'm an animal and I'm {} years old".format(self.age)
animal1 = Animal (5)
animal2 = Animal (7)
animal3 = Animal (3)
print(animal1)
# I'm an animal and I'm 5 years old
Animal.one_year_more()
print(animal1)
print(animal2)
# I'm an animal and I'm 6 years old
# I'm an animal and I'm 8 years old
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With