前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(二十九) 初遇python OOP面向对象编程-属性装饰器

(二十九) 初遇python OOP面向对象编程-属性装饰器

作者头像
XXXX-user
修改2019-07-30 10:46:49
3060
修改2019-07-30 10:46:49
举报
文章被收录于专栏:不仅仅是python不仅仅是python

各位读者大大们大家好,今天学习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的面向对象编程-属性装饰器学习就到这里!

关注公号

下面的是我的公众号二维码图片,欢迎关注。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 yale记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 关注公号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档