getting all user defined attributes of a class

grflanagan grflanagan at yahoo.co.uk
Thu Feb 7 03:28:41 EST 2008


On Feb 6, 11:07 pm, Amit Gupta <emaila... at gmail.com> wrote:
> Hi
>
> How do I get user defined attributes of a class? e.g
>
> Class A(object) :
>   self.x = 1
> ------------------
>
> I want something like:
>   for userattrib in A.getAllUserAttribute() :
>     print userattrib
>


class Meta(type):

    def __init__(cls, name, bases, attrs):
        super(Meta, cls).__init__(name, bases, attrs)
        cls._attrs = attrs.keys()


class Base(object):
    __metaclass__ = Meta

    def getmembers(self):
        return [k for k in self.__dict__ if k not in self._attrs]

class MyObj(Base):

    def __init__(self):
        self.a = 1
        self.b = 2

obj = MyObj()

print obj.getmembers()

['a', 'b']

setattr(obj, 'c', 3)

print obj.getmembers()

['a', 'c', 'b']

HTH

Gerard



More information about the Python-list mailing list