这种变形的特点:
1,在类外部无法直接obj.__AttrName
2,在类内部可以直接使用:obj.__AttrName
3,子类无法覆盖父类__开头的属性
0,
class A:
'类的封装啊'
__x = 1 # _A__x = 1
print('你去吃啥饭0000')
def __init__(self,name):
print('执行__init__')
self.__name = name # self._A__name = name
def __foo(self): # def _A__foo
print('run foo')
print('你去吃啥饭__foo')
def bar(self):
print('你去吃啥饭bar')
self.__foo()
print('from Bar')
print(A.__dict__)
a = A('egon')
# print(A._A__foo(a))
# a._A__foo()
# a.bar()
print(a._A__name)
# print(a.__name)
# # a._A__foo()
print('隐藏了呢',a._A__x)
输出:
你去吃啥饭0000
{'__module__': '__main__', '__doc__': '类的封装啊', '_A__x': 1, '__init__': <function A.__init__ at 0x000001BD2399D0D0>, '_A__foo': <function A.__foo at 0x000001BD2399D158>, 'bar': <function A.bar at 0x000001BD2399D1E0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>}
执行__init__
egon
隐藏了呢 1
1,
class Foo:
def __func(self): # _Foo__func
print('from foo')
class Bar(Foo):
def __func(self): # _Bar__func
print('from bar')
b = Bar()
b._Bar__func()
b._Foo__func()
输出:
from bar
from foo
2,
class B:
__x = 1
def __init__(self,name): # _Bar__func
self.__name = name # self._B__name = name
def pirnt(self):
print('你好啊',self.__z)
print(B._B__x)
B.__y = 2
print(B.__dict__)
b = B('egon')
print(b.__dict__)
b.__age = 18
print(b.__dict__)
print(b.__age)
B._B__z = 2
# B.pirnt(b)
b.pirnt()
print(B.__dict__)
输出:
1
{'__module__': '__main__', '_B__x': 1, '__init__': <function B.__init__ at 0x000002B30320D0D0>, 'pirnt': <function B.pirnt at 0x000002B30320D158>, '__dict__': <attribute '__dict__' of 'B' objects>, '__weakref__': <attribute '__weakref__' of 'B' objects>, '__doc__': None, '__y': 2}
{'_B__name': 'egon'}
{'_B__name': 'egon', '__age': 18}
18
你好啊 2
{'__module__': '__main__', '_B__x': 1, '__init__': <function B.__init__ at 0x000002B30320D0D0>, 'pirnt': <function B.pirnt at 0x000002B30320D158>, '__dict__': <attribute '__dict__' of 'B' objects>, '__weakref__': <attribute '__weakref__' of 'B' objects>, '__doc__': None, '__y': 2, '_B__z': 2}
3 封装执行顺序
class A:
def foo(self):
print('A.foo')
def bar(self):
print('A.bar')
self.foo() #b.foo()
class B(A):
def foo(self):
print('B.foo')
b = B()
b.bar()
print('-----------------------------------------------------------')
class A:
def __foo(self): # _A__foo
print('A.foo')
def bar(self):
print('A.bar')
self.__foo() # self._A.foo()
class B(A):
def __foo(self): # _B__foo
print('B.foo')
b = B()
b.bar()
输出:
A.bar
B.foo
-----------------------------------------------------------
A.bar
A.foo
标签:__,.__,封装,python,self,print,bar,foo
From: https://www.cnblogs.com/heris/p/16804913.html