【问题标题】:Getting property named `foo`获取名为`foo`的属性
【发布时间】:2016-05-25 13:41:52
【问题描述】:

我有

class A:

    foo = 'f'
    baa = 'b'

    @property
    def foo(self):
        return self.foo

    @property
    def baa(self):
        return self.baa

我想做这个程序:

get(myclass, prop):

获取类的属性。 例如a = A()get(a, 'foo') 给我fa = 2gets(a, 'imag') 给了我0

【问题讨论】:

  • 我投票决定将此问题作为题外话结束,因为目前尚不清楚您是否需要阅读有关 python oop 的介绍性书籍,您正在尝试做一些您没有告诉我们的详细说明,或者这是否是一个严重的 XY 问题。

标签: python properties


【解决方案1】:

内置函数名为getattr

您还需要以不同的方式调用属性和变量:

您无法使用getattr 访问属性

class A:
    def __init__(self):
        self._foo = 'f'
        self._bar = 'b'

    @property
    def foo(self):
        return self._foo

    @property
    def bar(self):
        return self._bar

a = A()
print(a.foo)
print(getattr(a, '_foo'))

【讨论】:

    【解决方案2】:

    正如@MaxNoe 所说,您想要的方法是getattr()。但是,如果您只想使用 get() 代替,您可以为其创建一个别名。显然也适用于类实例。

    #accepts class name (c) and attribute (attr)
    def get(c,attr):
        #returns the attribute
        return getattr(c,attr)
    

    Flask 使用(强制?)

    from flask import Flask
    app=Flask(__name__)
    
    @app.route("/")
    def get(c,attr):
        return getattr(c,attr)
    

    【讨论】:

    • 如何在flask中使用?
    • get = getattr 无需定义新函数即可创建别名。
    • 我的模板中有jinja2.exceptions.UndefinedError: 'getattr' is undefined{{getattr(r,f)}}。 (f 是 str,r 是类)
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2013-02-17
    • 2012-01-08
    相关资源
    最近更新 更多