python類里的私有變量如何定義?
python沒有私有變量,任何定義的變量都是可以直接調用的,但是一般來說,在定義的變量前后加上兩個下劃線,把這樣的變量當成是私有變量,如下代碼所示:
class person: def __init__(self): self.__private__ = 100p = person()print('__private__:', p.__private__)print('p包含的變量: ',dir(p))
輸出:
__private__: 100p包含的變量: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__private__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']