Use*_*123 4 python class python-3.x
我如何制作一个名为nextyear()的函数,将所有动物的年龄增加1?
class Animal:
def __init__(self, age):
self.age=age
animal1 = Animal (5)
animal2 = Animal (7)
animal3 = Animal (3)
Run Code Online (Sandbox Code Playgroud)
你可以使用类变量和属性:
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)
Run Code Online (Sandbox Code Playgroud)