python - 如何将一个类中所有对象共享的变量增加 1?

标签 python python-3.x class

我如何编写一个名为 nextyear() 的函数,使所有动物的年龄增加 1?

class Animal:
  def __init__(self, age):
    self.age=age
animal1 = Animal (5)
animal2 = Animal (7)
animal3 = Animal (3)

最佳答案

你可以使用一个类变量和一个属性:

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)

关于python - 如何将一个类中所有对象共享的变量增加 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310223/

相关文章:

Python 线程并行化逃离 GIL

python /套接字 : How to send a file to another computer which is on a different network?

python - 在 Python 中调用 Bing 或 IBM 文本转语音 API?

python - 密码验证在 django-rest-framework 中不起作用

Python BeautifulSoup 使用 data-reactid 查找

python - collections.abc.Callable 在 Python 3.9.1 中是否被窃听?

像excel一样的Python字符串序列

swift - Swift 中仅限类的泛型约束

python - 如何定义我只想在 __init__ 方法中使用的 Python 方法,即不能从类定义外部访问的方法?

javascript - Sorttable.js 适用于所有表格