python 06.20
1.类的封装
封装:隐藏属性或方法,外部无法使用,内部可以使用,在类定义阶段就执行了,真的想引用,就使用_类名__属性名
class Foo:
def __f1(self): #_Foo__f1
print('Foo.f1')
def f2(self): # Foo
print('Foo.f2')
self.__f1()
print(Foo.__dict__)
class Bar(Foo):
def __f1(self):
print('Bar.f1')
bar = Bar()
bar.f2() #Foo.f2
隐藏模块内的函数/变量_x: from module import _x (不合理)
2.类的property特性
@property: 被@property 装饰的函数会从函数变成属性,也就是说直接.函数名,不需要加括号调用
@方法名.setter :被@方法名.setter装饰的函数,方法名修改会执行这个装饰的函数
@方法名。deleter: 被@方法名.deleter装饰的函数,方法名删除,会执行这个装饰的函数
class People:
def __init__(self,height,weight):
self.height = height
self.weight = weight
@property #获取值的时候触发,你不需要加括号使用,不能加参数
def bmi(self):
return self.weight/(self.height**2)
@bmi.setter #在修改bmi的时候触发,必须得加参数
def bmi(self,value):
print(f'你已经成功修改为{value}')
@bmi.deleter #在删除bmi的时候触发,不能加参数
def bmi(self):
print('deleter')
peo = People(1.8,70)
print(peo.bmi)
print('*'*50)
peo.bmi = 50
print('*'*50)
del peo.bmi
3.类与对象的绑定与非绑定方法
class Foo:
#绑定给对象,只有对象能用,但是类也能使用,使用的时候必须得传参
def f1(self):
print(self)
@classmethod #让被装饰的函数给类使用,约定俗称参数为cls
#绑定给类的方法,类能使用,对象也能使用,但是参数依然是类
def f2(cls):
print(cls)
#什么都不绑定的,非绑定方法,定义了普通的函数
@staticmethod
def f3(self):
print(self)
f = Foo()
f.f1()
Foo.f1('参数')
print('*'*50)
Foo.f2()
f.f2()
print('*'*50)
Foo.f3('参数')
f.f3('参数')

浙公网安备 33010602011771号