【发布时间】: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__ 的第一个请求可能没问题,但我需要将author 和name 设置为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