Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从类属性组合函数_Python_Function_Attributes - Fatal编程技术网

Python 从类属性组合函数

Python 从类属性组合函数,python,function,attributes,Python,Function,Attributes,我是一个学习Python的普通Lisp程序员。我希望能够从部件构造函数。例如,如果我有一个具有属性的类,那么我可以使用点表示法来访问类实例的属性值,但显然我不能构建一个函数来做同样的事情。对于下面的代码,我可以请求a.attr1,但bar(a,attr1)不起作用 class foo (object): def __init__(self, x, y): self.attr1 = x self.attr2 = y a = foo(17,23) prin

我是一个学习Python的普通Lisp程序员。我希望能够从部件构造函数。例如,如果我有一个具有属性的类,那么我可以使用点表示法来访问类实例的属性值,但显然我不能构建一个函数来做同样的事情。对于下面的代码,我可以请求a.attr1,但bar(a,attr1)不起作用

class foo (object):
    def __init__(self, x, y):
        self.attr1 = x
        self.attr2 = y

a = foo(17,23)

print a.attr1

def bar (obj, fun):
    print obj.fun

bar(a, attr1)
NameError:未定义名称“attr1”

毫无疑问,我并没有以“pythonic”的方式思考,但一个稍微复杂一点的例子说明了我为什么要这样做。假设我想返回按属性排序的dict中的值:

d = {}
d['a'] = foo(17,23)
d['b'] = foo(13,19)

for v in sorted(d.values(), key = lambda x: x.attr1): print v.attr1
这可以正常工作,但以下函数无法正常工作:

def baz (dict,attr):
    for v in sorted(dict.values(), key = lambda x: x.attr): print v.attr1

baz(d,attr1)
NameError:未定义名称“attr1”

在CommonLisp中,我会引用attr1,但Python中似乎没有类似的功能。有什么建议吗?谢谢

def bar(obj, fun):
    print(getattr(obj, fun))

bar(a, 'attr1')
问题是python无法识别attr1,这是一个很好的理由——没有这样的符号

同样地:

def baz(d, attr):
    for v in sorted(d.values(), key = lambda x: getattr(x, attr)):
        print(v.attr1)

>>> d = { 'a':foo(17,23), 'b':foo(13,19) }
>>> baz(d, 'attr1')
13
17

大多数时候,如果你在做这些事情,你实际上需要的是一本简单的字典。

谢谢你,Elazar,这很管用。getattr是从属性组成函数的标准方法吗?谢谢。标准的方法是硬编码,但是可以。如果您需要动态的东西,应该使用
getattr
。这就是为什么它是一个很好的例子。