我想从基类访问类字段中的值。怎么做?看看我的代码:
class MyBase(object):
def p(self):
members = [attr for attr in dir(self) if not callable(getattr(self, attr)) and not attr.startswith("__")]
print members
class UserTest(MyBase):
def __init__(self, name='', family='', age=''):
self.name = name
self.family = family
self.age = age
a = UserTest(name='ehsan', family='shirzadi', age=29)
a.p()
使用上面的代码,我可以在执行a.p()之后看到变量名,但是如何看到它们的值呢?请考虑我不知道字段的名称,所以我不能使用姓名在基类中
这应该起作用:
在
MyBase.p
中执行callable(getattr(self, attr))
时,已经获得一次值。您可以使用相同的方法来获取输出的值:或者可以使用^{} 而不是^{} :
两者都会产生如下结果:
事实上,
vars
会为您提供一个字典,其中包含一些已提交的不需要的成员:或者只是:
收益率:
相关问题 更多 >
编程相关推荐