Python:如何在基类的方法中获取子类的新属性名称?

wal*_*tes 5 python attributes subclass

我想将子类中的所有属性名称放入列表中,我想在基类中执行此操作。我怎样才能做到这一点?我现在的方法是:

class Base():
    def __init__(self):
        # print SubClass' new attribues' names ('aa' and 'bb' for example)
        for attr in dir(self):
            if not hasattr(Base, attr):
                print attr

class SubClass(Base):
    aa = ''
    bb = ''
Run Code Online (Sandbox Code Playgroud)

有更好的方法吗?


谢谢你的帮助。

agf*_*agf 5

正如 @JohnZwinck 在评论中建议的那样,如果您需要这样做,那么您几乎肯定会犯一个设计错误。但是,如果没有更多信息,我们无法诊断问题。

这似乎是做你想做的事情的最简单的方法:

class Base(object):
    cc = '' # this won't get printed
    def __init__(self):
        # print SubClass' new attribues' names ('aa' and 'bb' for example)
        print set(dir(self.__class__)) - set(dir(Base))

class SubClass(Base):
    aa = ''
    bb = ''


foo = SubClass()
# set(['aa', 'bb'])
Run Code Online (Sandbox Code Playgroud)

self.__class__您需要而不是self测试新属性的原因是:

class Base(object):
    cc = ''
    def __init__(self):
        print set(dir(self)) - set(dir(Base))
        # print SubClass' new attribues' names ('aa' and 'bb' for example)

class SubClass(Base):
    def __init__(self):
        self.dd = ''
        super(SubClass, self).__init__()
    aa = ''
    bb = ''


foo = SubClass()
# set(['aa', 'dd', 'bb'])
Run Code Online (Sandbox Code Playgroud)

如果您希望定义的类之间存在差异,则需要使用__class__. 如果不这样做,您将得到不同的结果,具体取决于您检查新属性的时间