如何访问基类中的类字段值?

2024-09-28 03:15:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从基类访问类字段中的值。怎么做?看看我的代码:

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()之后看到变量名,但是如何看到它们的值呢?请考虑我不知道字段的名称,所以我不能使用姓名在基类中


Tags: 代码nameselfageobjectdefnot基类
2条回答

这应该起作用:

class MyBase(object):
    def p(self):
        print vars(self)

MyBase.p中执行callable(getattr(self, attr))时,已经获得一次值。您可以使用相同的方法来获取输出的值:

class MyBase(object):
    def p(self):
        print [(attr, getattr(self, attr)) for attr in dir(self)
            if not callable(getattr(self, attr)) and not attr.startswith('__')]

或者可以使用^{}而不是^{}

class MyBase(object):
    def p(self):
        print [(attr, value) for attr, value in vars(self).items()
            if not callable(value) and not attr.startswith('__')]

两者都会产生如下结果:

[('age', 29), ('name', 'ehsan'), ('family', 'shirzadi')]

事实上,vars会为您提供一个字典,其中包含一些已提交的不需要的成员:

class MyBase(object):
    def p(self):
        print vars(self)

或者只是:

a = UserTest(name='ehsan', family='shirzadi', age=29)
print vars(a)

收益率:

{'age': 29, 'name': 'ehsan', 'family': 'shirzadi'}

相关问题 更多 >

    热门问题