클래스의 모든 인스턴스에 함수를 적용하는 방법을 찾고 있습니다. 예 : 클래스의 모든 인스턴스에 함수 적용
class my_class:
def __init__(self, number):
self.my_value = number
self.double = number * 2
@staticmethod
def crunch_all():
# pseudocode starts here
for instances in my_class:
instance.new_value = instance.my_value + 1
그래서 명령
my_class.crunch_all()
기존의 모든 인스턴스에 새로운 속성
new_value
을 추가해야합니다. 나는 이것을 "글로벌"기능으로 만들기 위해
@staticmethod
을 사용해야 할 것이라고 추측합니다.
은 내가 my_class.instances
을 통해 다음 루프를 __init__
에 my_class.instances.append(number)
같은 것을 추가하고 의해 정의되고있는 인스턴스를 추적 할 수 알지만, 나도 지금까지 그와 운이 없었다. 또한 좀 더 일반적인 것이 있는지 궁금합니다. 이것은 가능한가?
이 있어야 '@classmethod'가 아니라'@ staticmethod'입니다. 그리고 네, 클래스 속성에서 클래스의 모든 인스턴스를 추적해야합니다. – jonrsharpe