class Foo:
__x = 1 # _Foo__x
def __f1(self): # _Foo__f1
print(‘from test‘)
print(Foo.__dict__) # {‘__module__‘: ‘__main__‘, ‘_Foo__x‘: 1, ‘_Foo__f1‘: <function Foo.__f1 at 0x00C683D0>, ‘__dict__‘: <attribute ‘__dict__‘ of ‘Foo‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘Foo‘ objects>, ‘__doc__‘: None}
print(Foo._Foo__x) # 1
print(Foo._Foo__f1) # <function Foo.__f1 at 0x00C683D0>
class Foo:
__x = 1 # _Foo__x = 1
def __f1(self): # _Foo__f1
print(‘from test‘)
def f2(self):
print(self.__x) # print(self._Foo__x)
print(self.__f1) # print(self._Foo__f1)
# print(Foo.__x) # AttributeError: type object ‘Foo‘ has no attribute ‘__x‘
# print(Foo.__f1) # AttributeError: type object ‘Foo‘ has no attribute ‘__f1‘
obj=Foo() # 1
obj.f2() # <bound method Foo.__f1 of <__main__.Foo object at 0x0143B070>>
class Foo:
__x = 1 # _Foo__x = 1
def __f1(self): # _Foo__f1
print(‘from test‘)
def f2(self):
print(self.__x) # print(self._Foo__x)
print(self.__f1) # print(self._Foo__f1)
Foo.__y=3
print(Foo.__dict__) # {‘__module__‘: ‘__main__‘, ‘_Foo__x‘: 1, ‘_Foo__f1‘: <function Foo.__f1 at 0x033A8418>, ‘f2‘: <function Foo.f2 at 0x033A83D0>, ‘__dict__‘: <attribute ‘__dict__‘ of ‘Foo‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘Foo‘ objects>, ‘__doc__‘: None, ‘__y‘: 3}
print(Foo.__y) # {‘__module__‘: ‘__main__‘, ‘_Foo__x‘: 1, ‘_Foo__f1‘: <function Foo.__f1 at 0x033A8418>, ‘f2‘: <function Foo.f2 at 0x033A83D0>, ‘__dict__‘: <attribute ‘__dict__‘ of ‘Foo‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘Foo‘ objects>, ‘__doc__‘: None, ‘__y‘: 3}
class Foo:
__x = 1 # _Foo__x = 1
def __init__(self, name, age):
self.__name = name
self.__age = age
obj = Foo(‘egon‘, 18)
print(obj.__dict__) # {‘_Foo__name‘: ‘egon‘, ‘_Foo__age‘: 18}
# print(obj.name, obj.age) # AttributeError: ‘Foo‘ object has no attribute ‘name‘
# 设计者:egon
class People:
def __init__(self, name):
self.__name = name
def get_name(self):
# 通过该接口就可以间接地访问到名字属性
# print(‘小垃圾,不让看‘)
print(self.__name)
def set_name(self,val):
if type(val) is not str:
print(‘小垃圾,必须传字符串类型‘)
return
self.__name=val
# 使用者:王鹏
obj = People(‘egon‘)
# print(obj.name) # 无法直接用名字属性
# obj.set_name(‘EGON‘)
obj.set_name(123123123)
obj.get_name()
# II、隐藏函数/方法属性:目的的是为了隔离复杂度
原文:https://www.cnblogs.com/xuexianqi/p/12660101.html