【问题标题】:Dynamic list properties of a class and ask for theses values类的动态列表属性并要求这些值
【发布时间】:2015-12-09 14:13:51
【问题描述】:

我对python很陌生,尝试写一个模块/

我尝试动态请求我的类的所有属性/属性,然后我想请求该值,但我无法获得我想要的结果。

目标:拥有一个属性列表。在这个例子中,它将是 姓名和作者

在询问这些值之后 名称:'我的第一个应用' 作者:“我”。

如果我运行这段代码,我将在第 39 行引发异常:

request = my_app + '.' + attribute TypeError: unsupported operand type(s) for +: 'Application' and 'str'

我尝试使用str(my_app),但它当然不起作用,因为对对象的引用已经消失。

带有__dict__ 的第一个请求可能没问题,但我需要将authorname 设置为dict.keys,而不是_Application__author_Application__name

这是一个简单的询问示例,但在我的模块中我有很多属性。

也许有人有线索?

class Application(object):
    def __init__(self, name,author=''):
        self.__name = name
        self.__author = author

    # ----------- NAME -------------
    @property
    def name(self):
        "Current name of the model"
        return self.__name

    @name.setter
    def name(self, name):
        self.__name = name

    @name.deleter
    def name(self):
        pass

    # ----------- AUTHOR -------------
    @property
    def author(self):
        "Current author of the model"
        return self.__author

    @author.setter
    def author(self, author):
        self.__author = author

    @author.deleter
    def author(self):
        pass

my_app = Application('my first app',author='me',)

print my_app.__dict__

for attribute in dir(my_app):
    if not attribute.startswith('__'):
        if not attribute.startswith('_'):
            if not attribute == 'instances':
                request =  my_app + '.' + attribute

结果

{'_Application__author': 'me', '_Application__name': 'my first app'}

Traceback (most recent call last):
  File "/Users/reno/Desktop/testtt.py", line 42, in <module>
    request =  my_app + '.' + attribute
TypeError: unsupported operand type(s) for +: 'Application' and 'str'
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "/Users/reno/Desktop/testtt.py"]
[dir: /Users/reno/Desktop]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

【问题讨论】:

    标签: python class properties


    【解决方案1】:

    my_appApplication 的一个实例,它的类型Application。另一方面,'.'type 的字符串。

    现在,当您使用+ 添加两个内容时,Python 需要知道如何添加这些内容。对于数字,它知道如何做到这一点。对于字符串,它也知道这一点:它只会连接它们。

    但是Applicationstring 之间没有定义加法。因此,您会收到错误消息。

    另外,为什么在

    的最后一个参数后面加逗号
    my_app = Application('my first app',author='me',)
    

    ?

    【讨论】:

    • 我知道添加不是正确的方法,但它是为了解释我想要做什么。
    • 逗号是一个疏忽,因为我删除了我的类的许多属性以尽可能短并专注于问题......感谢@Konstantin 看看我的问题!
    • @reno- 我认为你的问题很好,我只是没有正确阅读:)
    【解决方案2】:

    好的,答案是使用getattr方法。

    我刚刚用这一行替换了最后一行,它就像一个魅力。

                    print attribute , ':' , getattr(my_app, attribute)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      相关资源
      最近更新 更多