Pyhton-@property装饰器-__getattr__()-__getattribute()

2023-05-17 09:25:10 浏览数 (2)

@property

pyton内置的@property装饰器可以把一个方法变成一个属性

代码语言:javascript复制
class User:
    def __init__(self):
        self.username='admin'
        self.password='123456'

    @property
    #pyton内置的@property装饰器可以把一个方法变成一个属性,通过user.info调用
    def info(self):
        return [self.username,self.password]
user= User()
print(user.info)

getattr()

如果存在getattr()的定义,访问object不存在的属性时会调用该方法,相当于php的__get()魔法函数 不存在定义时,访问不存在的属性会报 AttributeError

代码语言:javascript复制
class User:
    def __init__(self):
        self.uname='admin'
if __name__ == "__main__":
    user = User()
    print(user.passwd)

#output:
#AttributeError: 'User' object has no attribute 'passwd'
代码语言:javascript复制
class User:
    def __init__(self):
        self.uname='admin'
    def __getattr__(self, item):
        print(item,'not exits')
        return self.uname
if __name__ == "__main__":
    user = User()
    print(user.passwd)
#output:
#passwd not exits
#admin

getattribute()

__getattribute_是属性访问拦截器,就是当这个类的属性被访问时,会自动调用类的getattribute方法,相当于一个filter

代码语言:javascript复制
class User:
    def __init__(self):
        self.uname='admin'
    def __getattribute__(self, item):
        print(item,'t',end='')
        if item == 'uname':
            return 'admin'
        else:
            return 'not exits'
if __name__ == "__main__":
    user = User()
    print(user.uname)
    print(user.passwd)

#output:
#uname  admin
#passwd     not exits

python对象自省机制

代码语言:javascript复制
class User:
    uname='Admin'
    def __init__(self):
        self.uname='admin'

if __name__ == "__main__":
    user = User()
    print(user.uname)
    #打印对象的全部属性和值
    print(user.__dict__)
    #打印类的全部属性和值
    print(User.__dict__)
    #打印对象里的所有属性(只会打印出属性名称,不打印属性的值)
    print(user.__dir__())

#output:
# admin
# {'uname': 'admin'}
# ['uname', '__module__', '__init__', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
# {'__module__': '__main__', 'uname': 'Admin', '__init__': <function User.__init__ at 0x000001EF86143040>, '__dict__': <attribute '__dict__' of 'User' objects>, '__weakref__': <attribute '__weakref__' of 'User' objects>, '__doc__': None}

0 人点赞