1、@staticmethod # 类内部调用静态方法
class A(object): def __init__(self, name): self.name = name @staticmethod def talk(): print(‘talk‘.center(50, ‘-‘)) A.talk() # 直接调用方法,不需要实例化 输出:-----------------------talk-----------------------
2、类特殊方法: __getitem__、__setitem__、__delitem__、__call__
class Person(object): """ 自定义Person类 """ age = ‘22‘ sex = ‘male‘ def __init__(self, name): """构造方法""" self.name = name def __call__(self): """调用对象时执行""" print(‘My name is %s.‘ % self.name) def __getitem__(self, item): print(‘get item‘, item) def __setitem__(self, key, value): print(‘Set %s : [ %s ].‘ % (key, value)) self.name = value def __delitem__(self, key): print(‘Delete %s.‘ % key) del key person = Person(‘bloke‘) person() # 调用__call__方法 person[‘name‘] = ‘user01‘ # 调用__setitem__方法 person[‘name‘] # 调用__getitem__方法 del(person[‘name‘]) # 调用__delitem__方法
# 输出:
My name is bloke.
Set name : [ user01 ].
get item name
Delete name.
3、@property 属性函数,将类方法变为类属性的装饰器,在不动源代码构造结构时,将获取信息、修改信息、删除信息封装成一个接口,以供调用
class Person(object): def __init__(self, name, age): self.name = name self.age = age @property def info(self): return(‘Name: %s, Age: %s‘ % (self.name, self.age)) @info.setter def info(self, name): self.name = name return(‘Name: %s, Age: %s.‘ % (self.name, self.age)) @info.deleter def info(self): del self.age person = Person(‘bloke‘, ‘22‘) # 实例化 print(person.info) # Name: bloke, Age: 22 person.info = ‘user01‘ #赋值 print(person.info) # Name: user01, Age: 22 del person.info # 删除age print(person.info) # 抛出异常,没有age属性 # 也可以使用: info = property(get, set, del) 将类的get、set、del方法封装成info接口
4、反射,通过字符串形式来调用类方法
hasattr(obj, attr) # 判断obj是否有attr属性 getattr(obj, attr, default) # 获取obj的attr属性,默认输出default delattr(obj, attr) # 删除obj的attr属性 setattr(obj, attr, value) # 设置obj的attr属性的值为value