【发布时间】:2018-01-25 20:04:54
【问题描述】:
假设我有一个如下所示的类,
class TestClass(object):
def __init__(self):
self.name = 'Marty'
self.age = 25
self.place = 'CL'
@property
def country(self):
return 'USA'
@property
def age_group(self):
return '18-25'
我想从所有@properties 中创建一个字典。我尝试过使用__dict__ 和vars,但@property 仍然没有出现。我怎样才能包括@property。
>>> x = TestClass()
>>> x.__dict__
{'age': 25, 'name': 'Marty', 'place': 'CL'}
>>> vars(x)
{'age': 25, 'name': 'Marty', 'place': 'CL'}
我想将age_group 和country 包含在返回值中作为键和值。
【问题讨论】:
-
您可以访问 TestClass.__dict__ 上的属性。所以我想你可以遍历这些并添加名称如果
type == property
标签: python class object properties