本文将简单介绍四种获取对象的方法。
假如有以下的类:
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return 'name=%s, age=%s' % (self.name, self.age)
xmr = Person('lisi',12)
print(xmr.name)
print(xmr.__dict__['name'])
print(getattr(xmr, 'name'))
import operator
op = operator.attrgetter('name')
print(op(xmr))
import operator
p_list = [Person('xiemanR', 18), Person('zhangshan', 17), Person('lisi', 20), Person('wangwu', 25)]
r = sorted(p_list, key=operator.attrgetter('age'))
for i in r:
print(i)
输出结果:
Person(name=zhangshan, age=17)
Person(name=xiemanR, age=18)
Person(name=lisi, age=20)
Person(name=wangwu, age=25)