Python: how to get subclass's new attributes name in base class's method?

只谈情不闲聊 提交于 2019-12-24 05:18:10

问题


I want to put all attribute names in SubClass to a list, I want to do that in Base class. How can I do that? My method now is:

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 = ''

is there a better way to do that ?


Thanks for any help.


回答1:


As the @JohnZwinck suggested in a comment, you're almost certainly making a design mistake if you need to do this. Without more info, however, we can't diagnose the problem.

This seems the simplest way to do what you want:

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'])

The reason you need self.__class__ instead of self to test for new attributes is this:

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'])

If you want the difference between the classes as defined, you need to use __class__. If you don't, you'll get different results depending on when you check for new attributes.



来源:https://stackoverflow.com/questions/7136154/python-how-to-get-subclasss-new-attributes-name-in-base-classs-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!