Skip to content Skip to sidebar Skip to footer

Python: How To Get Subclass's New Attributes Name In Base Class's Method?

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

Solution 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:

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

classSubClass(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.

Post a Comment for "Python: How To Get Subclass's New Attributes Name In Base Class's Method?"