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):删除一个实例对象的属性时调用
*