其他分享
首页 > 其他分享> > 属性的管理机制

属性的管理机制

作者:互联网

私有属性:

以双下划线开头的属性称为私有属性,私有属性只能在类的里面被调用,在类的外面不能直接被调用

class My:
    __a=50
    name="tom"

print(My.__dict__)
print(My.name)
print(My__a)  #会报错,提示没有这个属性
print(My._My__a) #调用私有属性要加上_My

 

内置属性__slots__:

限制对象的属性,只能绑定slots指定的属性,不能添加slots之外的属性。__slots__只对当前定义的类生效,不会被继承

__slots__=["name","age"]

 

__dict__:

类调用__dict__属性,返回类属性和方法的字典

实例调用__dict__属性,返回实例相关的实例属性

点击查看代码
class MyTest(object):
    __slots__ = ["title", "money", "data", "age"]

    def __getattr__(self, item):
        # 获取属性,当属性不存在时才会自动调用__getattr__方法,不会报错返回None
        # 没有添加这个属性,获取属性当属性不存在会报错
        # 当获取的属性不存在时,如有返回值,获取的属性则为__getattr__返回值
        print('--------__getattr__方法--------------')
        raise AttributeError('MyTest object not {} attribute'.format(item))

    def __getattribute__(self, item):
        # 获取属性触发的魔术方法,不管属性值存不存在
        # 当属性不存在时会报错
        print('获取属性的方法-->item:', item)
        return super().__getattribute__(item)

    def __setattr__(self, key, value):
        # 设置属性的时候 触发的魔术方法   #重写__setattr__方法后没有设置属性,要再次调用父类的__setattr__方法设置属性
        # print('key:{},value:{}'.format(key, value))

        return super().__setattr__(key, value)

    def __delattr__(self, item):
        # 删除属性的时候 触发的魔术方法
        print("删除属性:", item)
            #在不调用父类的删除方法__delattr__时,就相当于没有实现删除功能
        # super().__delattr__(item)


m = MyTest()

# print('属性值:', m.name)
#调用__setattr__方法
# m.name = 'musen'
m.age = 18
# print(m.name, m.age)

del m.age
print('--------------删除后----------------------')
print( m.age)

标签:__,调用,管理机制,item,print,My,属性
来源: https://www.cnblogs.com/junhao86/p/15510567.html