继承的顺序从对象,在去类里面,在去父类里面
隐藏
#_*_coding:utf-8_*_
class A:
__x=1 #_A__x=1
def __init__(self,name):
self.__name = name #self._A__name='egon'
def __foo(self): #def _A__foo(self)
print('run foo')
def bar(self):
#这函数里面,就已经定义正确的调用格式了
self.__foo() #self._A__foo()
print('from bar')
#类名称空间
print(A.__dict__)
#a=A('egon')
#a._A__foo()
#a._A__x
# print(a.__name) #a.__dict__['_A__name']
#a.__foo()#直接报错了
#a.bar()
这种变形的特点
1、在类外部无法直接obj.__AttrName
2、在类内部是可以直接使用 a.bar()
3、子类无法覆盖父类__开头的属性
#_*_coding:utf-8_*_
class Foo:
def __func(self): #_Foo__func
print('from foo')
class Bar(Foo):
def __func(self): #_Bar__func
print('from bar')
#b=Bar()
#b.func()
#_*_coding:utf-8_*_
class B:
__x = 1
def __init__(self,name):
self.__name=name #self._B__name = name
#验证问题二
b = B('egon')
print(b.__dict__)
b.__age = 18
print(b.__dict__)
print(b.__age)
#_*_coding:utf-8_*_
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()
一、封装数据属性:明确的区分内外,控制外部对隐藏的属性的操作行为
#_*_coding:utf-8_*_
class People:
def __init__(self,name,age):
self.__name=name
self.__age=age
def tell_info(self):
print('Name:<%s> Age:<%s>' %(self.__name,self.__age))
def set_info(self,name,age):
if not isinstance(name,str):
print('名字必须是字符串类型')
return
if not isinstance(age,int):
print('年龄必须是数字类型')
return
self.__name=name
self.__age=age
p=People('egon',18)
p.tell_info()
# p.set_info('EGON',38)
# p.tell_info()
# p.set_info(123,38)
p.set_info('egon','38')
p.tell_info()
#_*_coding:utf-8_*_
class ATM:
def __card(self):
print('插卡')
def __auth(self):
print('用户认证')
def __input(self):
print('输入取款金额')
def __print_bill(self):
print('打印账单')
def __take_money(self):
print('取款')
def withdraw(self):
self.__card()
self.__auth()
self.__input()
self.__print_bill()
self.__take_money()
a=ATM()
a.withdraw()
#_*_coding:utf-8_*_
class Room:
def __init__(self,name,owner,weight,length,height):
self.name=name
self.owner=owner
self.__weight=weight
self.__length=length
self.__height=height
#我只想访问房间面价,在类不开一个接口计算面积
def tell_area(self):
return self.__weight * self.__length * self.__height
r=Room('卫生间','alex',10,10,10)
# print(r.tell_area())
print(r.tell_area())
1000