如果某个属性属于另一个类,如何获取vars
函数以返回class
的属性?
示例:
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.geo = GeoInformation()
class GeoInformation:
def __init__(self, city="", state="", zipcode="", country=""):
self.city = city
self.state = state
self.zipcode = zipcode
self.country = country
user = User("John", "Smith")
user.geo.city = "SomeCity"
user.geo.state = "SomeState"
user.geo.zipcode = "SomeZipcode"
user.geo.country = "SomeCountry"
print(vars(user))
我得到的输出:
{'first_name': 'John', 'last_name': 'Smith', 'geo': <class '__main__.GeoInformation'>}
我期望的输出:
{'first_name': 'John', 'last_name': 'Smith', 'geo': {'city':'someCity', 'state':'someState', 'zipcode':'someZipcode', 'country':'someCountry'}}
如果这不是我要实现的目标的正确方法,请提出更好的方法。
答案 0 :(得分:1)
这是一个递归运行vars
并返回结果的函数:
def recursive_vars(obj):
dct = vars(obj)
for k, v in dct.items():
if hasattr(obj, __dict__): # check if we can go further recursively
dct[k] = recursive_vars(v)
return dct
现在,应该使用该类产生的任何值vars()
替换作为类的任何值,依此类推。
答案 1 :(得分:0)
您可以在GeoInformation类中定义一个__repr__
方法,该方法本身会调用var,因此当您调用print(vars(user))
时,它还会在您的geo属性中打印出数据
class User:
def __init__(self, first_name, last_name,city, state, zipcode, country):
self.first_name = first_name
self.last_name = last_name
self.geo = GeoInformation(city, state, zipcode, country)
class GeoInformation:
def __init__(self, city="", state="", zipcode="", country=""):
self.city = city
self.state = state
self.zipcode = zipcode
self.country = country
def __repr__(self):
return str(vars(self))
user = User("John", "Smith","SomeCity","SomeState","SomeZipcode","SomeCountry")
print(vars(user))
输出:
{'first_name': 'John', 'last_name': 'Smith', 'geo': {'city': 'SomeCity', 'state': 'SomeState', 'zipcode': 'SomeZipcode', 'country': 'SomeCountry'}}