반응형
이 질문이 이벤트 처리와 관련이 있음을 알고 있으며 Python 이벤트 처리기 디스패처에 대해 읽었으므로 내 질문에 대답하지 않았거나 정보를 완전히 놓쳤습니다.
v
값이 변경 될 때마다 A
개체의 m ()
메서드가 트리거되기를 원합니다.
예를 들어 (돈이 행복하다고 가정) :
global_wealth = 0
class Person()
def __init__(self):
self.wealth = 0
global global_wealth
# here is where attribute should be
# bound to changes in 'global_wealth'
self.happiness = bind_to(global_wealth, how_happy)
def how_happy(self, global_wealth):
return self.wealth / global_wealth
따라서 global_wealth
값이 변경 될 때마다 Person
클래스의 모든 인스턴스는 그에 따라 happiness
값을 변경해야합니다.
주의 : 첫 번째 버전에서 getter 및 setter 메서드가 필요하다고 제안한 것 같아서 질문을 수정해야했습니다. 혼란을 드려 죄송합니다.
해결 방법
이 예제에서는 속성을 사용하지만 필수는 아닙니다. 작은 경고 : 속성은 새 스타일 클래스에서만 작동하므로 클래스 선언 뒤의 (객체)는 이것이 작동하는 데 필수입니다.
class GlobalWealth(object):
def __init__(self):
self._global_wealth = 10.0
self._observers = []
@property
def global_wealth(self):
return self._global_wealth
@global_wealth.setter
def global_wealth(self, value):
self._global_wealth = value
for callback in self._observers:
print('announcing change')
callback(self._global_wealth)
def bind_to(self, callback):
print('bound')
self._observers.append(callback)
class Person(object):
def __init__(self, data):
self.wealth = 1.0
self.data = data
self.data.bind_to(self.update_how_happy)
self.happiness = self.wealth / self.data.global_wealth
def update_how_happy(self, global_wealth):
self.happiness = self.wealth / global_wealth
if __name__ == '__main__':
data = GlobalWealth()
p = Person(data)
print(p.happiness)
data.global_wealth = 1.0
print(p.happiness)
참조 페이지 https://stackoverflow.com/questions/6190468
반응형
'파이썬' 카테고리의 다른 글
파이썬 python과 ssh 연결을 만드는 방법은 무엇입니까? (0) | 2020.10.01 |
---|---|
파이썬 How to implement an ordered, default dict? (0) | 2020.10.01 |
파이썬 What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)? (0) | 2020.10.01 |
파이썬 Python 사전 생성 구문 (0) | 2020.10.01 |
파이썬 목록에서 최대 값과 색인을 찾는 Pythonic 방법? (0) | 2020.10.01 |
댓글