定制属性的访问

定制属性访问的方法(增,删,改,查)

查:

  • hasattr(对象," 属性名 " ) 返回布尔值

  • getattr(对象," 属性名 " ) 有则返回 ,无则报错

  • 对象.__ getattibute __(" 属性名 " ) 有则返回 ,无则报错

  • **hasattr()**例子:

class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = A("人类", 100)
b = hasattr(a, "name")    #有该属性
c = hasattr(a, "sex")     #无该属性
print(b)
print(c)

结果:

True
False
  • **getattr()**例子
class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = A("人类", 100)
b = getattr(a, "name")
print(b)

结果:

人类
class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = A("人类", 100)
b = getattr(a, "sex")
print(b)

结果:

AttributeError: 'A' object has no attribute 'sex'
  • 对象.getattribute()
class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = A("人类", 100)
b = a.__getattribute__("name")
print(b)

b = a.__getattribute__("sex")
print(b)

结果:

人类
AttributeError: 'A' object has no attribute 'sex'

增,改

(有则改之,无则加勉)

  • 对象.属性名 = 值
  • setattr(对象," 属性名 ",目的修改值)
  • **对象.__ setattr __(“属性名”, ** 目的修改值)
1.
class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = A("人类", 100)
# 对象.属性名  改
a.name = "女娲"
print(a.name)
# 对象.属性名  增
a.sex = "女性"
print(a.sex)

结果:

女娲
女性
2.
class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = A("人类", 100)
# setattr()  改
setattr(a, "name", "女娲")
print(a.name)
# setattr()  增
setattr(a, "sex", "女性")
print(a.sex)

结果:

女娲
女性
3.
class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = A("人类", 100)
# setattr()  改
a.__setattr__("name", "女娲")
print(a.name)
# setattr()  增
a.__setattr__("sex", "女性")
print(a.sex)

结果:

女娲
女性

  • delattr(对象, “属性名”)
  • 对象.__ delattr __( “属性名”)
class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = A("人类", 100)
a.__setattr__("name", "女娲")
a.__setattr__("sex", "女性")
delattr(a, "name")
a.__delattr__("sex")

print(a.name)
print(a.sex)
AttributeError: 'A' object has no attribute 'name'
AttributeError: 'A' object has no attribute 'sex'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

捕获一只小肚皮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值