当前位置 博文首页 > m0_51723227的博客:定制属性的访问

    m0_51723227的博客:定制属性的访问

    作者:[db:作者] 时间:2021-08-09 10:04

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

    查:

    • 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'
    
    cs
    下一篇:没有了