Changing variables in multiple Python instances

后端 未结 4 433
感情败类
感情败类 2021-01-18 22:24

Is there anyway to set the variables of all instances of a class at the same time? I\'ve got a simplified example below:

class Object():
   def __init__(self         


        
4条回答
  •  被撕碎了的回忆
    2021-01-18 22:48

    "Is there any way to set the variables of all instances of a class at the same time?"

    That's a class attribute!

    Some examples on how to access a class attribute:

    >>> class Object:
    ...     speed = 5
    ...     @classmethod
    ...     def first(cls):
    ...         return cls.speed
    ...     def second(self):
    ...         return self.speed
    ...
    >>> Object.speed
    5 
    >>> instance = Object()
    >>> instance.speed
    5
    >>> instance.first()
    5
    >>> instance.second()
    5
    

提交回复
热议问题