Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase a variable shared by all objects in a class by 1?

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)
like image 948
User9123 Avatar asked Jan 29 '23 03:01

User9123


2 Answers

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)
like image 168
ktzr Avatar answered Jan 31 '23 11:01

ktzr


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
like image 23
Thierry Lathuille Avatar answered Jan 31 '23 11:01

Thierry Lathuille