各位读者大大们大家好,今天学习python的面向对象编程-属性装饰器,并记录学习过程欢迎大家一起交流分享。
新建一个python文件命名为py3_oop6.py,在这个文件中进行操作代码编写:
#面向对象编程
#属性装饰器
class Employee:
def __init__(self,first,last):
self.first = first
self.last = last
self.email = first + '.' + last +'@email.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
emp_1 = Employee('T','Bag')
#打印emp_1的信息
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())
#打印结果:
#T
#T.Bag@email.com
#T Bag
#接下来改变emp_1的first 属性值
emp_1.first = 'M'
#继续打印信息
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())
#M
#T.Bag@email.com
#M Bag
#我们发现emp_1的first名字和fullname()
#都会正常跟着改变
#但是email却还是老的first的值
#因为我们每次运行调用fullname()
#都会调用实例化对象的属性self.first和self.last
#这里我们希望email也跟着改变
#所以我们可以在创建一个email方法实现,
#并且使用属性装饰器@property修饰:
class Employee:
def __init__(self,first,last):
self.first = first
self.last = last
@property
def email(self):
return '{}.{}@email.com'.format(self.first,self.last)
@property
def fullname(self):
return '{} {}'.format(self.first,self.last)
#设置setter赋值方法
@fullname.setter
def fullname(self,name):
first,last = name.split(' ')
self.first = first
self.last = last
#设置deleter删除方法
@fullname.deleter
def fullname(self):
print('删除名字')
self.first = None
self.last = None
emp_1 = Employee('T','Bag')
#使用@property属性修饰的方法
#直接调用方法名不需要加()
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)
#T
#T.Bag@email.com
#T Bag
emp_1.first = 'M'
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)
#M
#M.Bag@email.com
#M Bag
#现在的结果显示email跟着正常改变
#为fullname属性赋值
emp_1.fullname ='Gas Tank'
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)
#Gas
#Gas.Tank@email.com
#Gas Tank
#删除全名
del emp_1.fullname
#删除名字
运行结果:
T
T.Bag@email.com
T Bag
M
T.Bag@email.com
M Bag
T
T.Bag@email.com
T Bag
M
M.Bag@email.com
M Bag
Gas
Gas.Tank@email.com
Gas Tank
删除名字
今天初学python的面向对象编程-属性装饰器学习就到这里!
下面的是我的公众号二维码图片,欢迎关注。