Python获取对象属性的4种方法

本文将简单介绍四种获取对象的方法。

假如有以下的类:

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)

方法一:使用属性运算符

print(xmr.name)

方法二:通过属性字典__dict__

print(xmr.__dict__['name'])

方法三:通过getattr函数

print(getattr(xmr, 'name'))

方法四:operator.attrgetter

import operator

op = operator.attrgetter('name')
print(op(xmr))

方法四可以用于对象的排序,比如需要根据年龄age来排序Person对象:

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)

PS:其实第四种方法是调用第三种方法的,只是简单封装了一下,我们看看operator.attrgetter实现就知道了:

class attrgetter:
    def __init__(self, attr, *attrs):
        if not attrs:
            if not isinstance(attr, str):
                raise TypeError('attribute name must be a string')
            names = attr.split('.')
            def func(obj):
                for name in names:
                    obj = getattr(obj, name)
                return obj
            self._call = func
        else:
            getters = tuple(map(attrgetter, (attr,) + attrs))
            def func(obj):
                return tuple(getter(obj) for getter in getters)
            self._call = func

    def __call__(self, obj):
        return self._call(obj)

完。

你可能感兴趣的:(Python,Python获取对象)