python __getattr__ 和__dict __, hasattr属性的用法

1.python __getattr

class adaptee(object):
    def foo(self):
        print('foo in adaptee')
        
    def bar(self):
        print('bar in adaptee')


class adapter(object):
    def __init__(self):
        self.adaptee = adaptee()

    def foo(self):
        print('foo in adapter')
        self.adaptee.foo()

    def __getattr__(self, name):
        return getattr(self.adaptee, name)


if __name__ == '__main__':
    a = adapter()
    a.foo()
    a.bar()

打印结果:
foo in adapter
foo in adaptee
bar in adaptee

2.python dict
类或对象中的所有属性----类的实例属性属于对象;类中的类属性和方法等属于类,即:

class Province(object):
    country = 'china'

    def __init__(self, name, count):
        self.name = name
        self.count = count

    def func(self, *args, **kwargs):
        print('func')


# 获取类的属性, 即:类属性,方法
print(Province.__dict__)
# 获取对象obj1的属性
obj1 = Province('山东', 10000)
print(obj1.__dict__)

打印结果
{‘dict’: <attribute ‘dict’ of ‘Province’ objects>, ‘module’: ‘main’, ‘weakref’: <attribute ‘weakref’ of ‘Province’ objects>, ‘country’: ‘china’, ‘doc’: None, ‘func’: <function Province.func at 0x000001D06BE7D048>, ‘init’: <function Province.init at 0x000001D06BE70F28>}
{‘count’: 10000, ‘name’: ‘山东’}

3.python hasattr
hasattr()函数用于判断对象是否包含对应的属性,hasattr(object, name)

class Coordinate(object):
    x = 10
    y = -5
    z = 0

point1 = Coordinate()
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no'))

打印结果
True
True
True
False

4.魔方方法
*1.getattr(self, name):访问不存在的属性时调用
2.getattribute(self, name):访问存在的属性时调用(先调用该方法,查看是否存在该属性,若不存在,接着去调用1)
3.setattr(self, name, value):设置实例对象的一个新的属性时调用
4.delattr(self, name):删除一个实例对象的属性时调用
*

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值