1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
class P(object): def __init__(self, v): print('init P') self.data = v def __get__(self, ins, cls): print(f'from ins:{ins.__dict__} get {self.data} & cls:{cls}') return self.data def __set__(self, ins, v): print(f'save {v} to {ins.__dict__}') self.data = v def __delete__(self, ins): del self.data class Person(): name = P('Alice') def __init__(self, v): print('init name') self.name = v print('init street') self.street = v
obj = Person('Bob') print(f'Does obj have name? { hasattr(obj, "name") }') print('-'*20) print(f'obj has:{obj.__dict__}') print(f'Does obj have name? { hasattr(obj, "name") }') print(f'Now will get name:{obj.name}') print('-'*20) print('Now will get street:{obj.street}') obj.name = 'Charley' print(f'Does obj have name? { hasattr(obj, "name") }') print(f'get name from {obj}: {obj.name}') print(f'del name') del obj.name print(f'Does obj have name? { hasattr(obj, "name") }') obj.name = 'Doggie' print(f'Does obj have name? { hasattr(obj, "name") }') print('-'*20) print(type(obj).__dict__['name'].__get__(obj, type(obj))) print('-'*20) print(type(obj).__dict__['name'].__get__(obj, type(obj)) is obj.name)
|