python基础语法 010 类和对象6-4 属性动态设置

2.6 属性动态设置

1)setattr:属性设置

setattr() function sets the value of the specified attribute of the specified object.

  • 参数1:对象
  • 参数2:属性名
  • 参数3:属性值
#设置 set属性
#setattr(phone,'number', '200')   === > phone.number = 200
setattr(phone,'number', '200')
print(phone.number)


#200

2)getattr:获取属性

  • 参数1:对象
  • 参数2:属性名

例子:

class Phone:

    def __init__(self, number):
        self.number = number
#第一种获取属性的方式:对象.属性
phone = Phone('1237')
print(phone.number)

#第二种动态获取属性的方式:getattr(object, name, default=None)
print(getattr(phone,'number'))
 getattr特点1:设置默认值,对于不存在的属性可以直接设置默认值

        问:当类中没有该属性,怎么处理?

#print(phone.brand)
#AttributeError: 'Phone' object has no attribute 'brand'

#print(getattr(phone,'brand'))
#AttributeError: 'Phone' object has no attribute 'brand'

#可以加上defau参数,设置默认值,当没有该属性时,就不会报错,而是返回默认值
print(getattr(phone,'brand', 'apple'))
#>>apple
 getattr特点2:把属性名可以定义为变量,属性名 == 变量


'如果 传递的属性名称是一个变量怎么获取? 通过传变量的形式获取属性名称'
prop_name = 'brand' #是一个变量
getattr(phone, prop_name, 'apple')
print(getattr(phone, prop_name, 'apple'))
#>>apple
 注意:
#并没有设置这个属性,只是因为属性没有,而尝试给他一个默认值
print(phone.brand)
#AttributeError: 'Phone' object has no attribute 'brand'

3)delattr:删除属性

  • 参数1:对象
  • 参数2:属性名

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值