存取 Python 私有函數與屬性 - tsungjung411/python-study GitHub Wiki
class A: __avg = None def __sum(self, a, b, c): print("a: ", a) print("b: ", b) print("c: ", c) sum = a + b + c print("sum(a, b, c)=", sum) self.__avg = sum / 3.0 return sum # end-of-def # end-of-class a = A() print("dir(A.__class__):\n", dir(A.__class__), '\n') print('--------------------------------------------') method_name = '_{}__sum'.format(a.__class__.__name__) print('method_name: ', method_name) method_pointer = a.__getattribute__(method_name) print('method_pointer: ', method_pointer) total = method_pointer print("total(1,2,3)= {}".format(total(1,2,3))) print('--------------------------------------------') field_name = '_{}__avg'.format(type(a).__name__) print('field_name: ', field_name) field_pointer = a.__getattribute__(field_name) print('field_pointer: ', field_pointer) print("avg(1,2,3)= {}".format(field_pointer))
執行結果:
dir(A.__class__): ['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__', '__weakrefoffset__', 'mro'] -------------------------------------------- method_name: _A__sum method_pointer: > a: 1 b: 2 c: 3 sum(a, b, c)= 6 total(1,2,3)= 6 -------------------------------------------- field_name: _A__avg field_pointer: 2.0 avg(1,2,3)= 2.0
特別說明:
- 若使用
dir(a.__class__)
印出所有屬性,不會有__name__
,要用dir(A.__class__)
才會有。