ehsan shirzadi
ehsan shirzadi

Reputation: 4859

How to access a class field values in its base class?

I want to access the values in a class fields from its base class. how to do it? look at my code:

class MyBase(object):

    def p(self):
        members = [attr for attr in dir(self) if not callable(getattr(self, attr)) and not attr.startswith("__")]
        print members

class UserTest(MyBase):
    def __init__(self, name='', family='', age=''):
        self.name = name
        self.family = family
        self.age = age

a = UserTest(name='ehsan', family='shirzadi', age=29)
a.p()

Using above code, I can see variable names after execution of a.p(), but how to see their values? Please consider that I don't know the name of fields, so I can't use self.name in the base class

Upvotes: 2

Views: 259

Answers (2)

famousgarkin
famousgarkin

Reputation: 14116

You already got the value once when doing callable(getattr(self, attr)) in MyBase.p. You can either use the same to get the value for the output:

class MyBase(object):
    def p(self):
        print [(attr, getattr(self, attr)) for attr in dir(self)
            if not callable(getattr(self, attr)) and not attr.startswith('__')]

or you can use vars instead of dir:

class MyBase(object):
    def p(self):
        print [(attr, value) for attr, value in vars(self).items()
            if not callable(value) and not attr.startswith('__')]

Both yield a result like:

[('age', 29), ('name', 'ehsan'), ('family', 'shirzadi')]

In fact, vars gets you a dictionary with some unwanted members already ommited:

class MyBase(object):
    def p(self):
        print vars(self)

or just:

a = UserTest(name='ehsan', family='shirzadi', age=29)
print vars(a)

yields:

{'age': 29, 'name': 'ehsan', 'family': 'shirzadi'}

Upvotes: 2

Jahaja
Jahaja

Reputation: 3302

This should work:

class MyBase(object):
    def p(self):
        print vars(self)

Upvotes: 1

Related Questions