Python: how to get subclass's new attributes n

2019-07-20 19:53发布

问题:

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.