Diego Aguado
Diego Aguado

Reputation: 1606

Automatic inheritance of all base class attributes

I want to create a class that has two characteristics:

I want these two characteristics because I want to automatically inherit all the attributes and methods of the previous object (base class object) without having to do something like use the __init__ method since this will cause recalculation of the already computed initialization. And since there will be a lot of methods and attributes I don't think its good practice to do it manually.

My idea of the code would look something like this.

class BaseClass(object):
     def __init__(self, name, date):
         self.name = name
         self.date = date

     def get_name_date(self):
         self.name_date = self.name +self.date

class UpperClass(BaseClass):
    def __init__(self):
        self.date_name = self.date + self.name

I know the code above will not work and I dont want to do something like:

class UpperClass(BaseClass):
    def __init__(self):
        super(BaseClass, self).__init__(name, date)
        self.date_name = self.date + self.name

Cause this will re-do calculations I already have. Maybe inheritance is not what I'm looking for, any pointers?

Upvotes: 0

Views: 104

Answers (1)

Thmei Esi
Thmei Esi

Reputation: 442

Is this what you are looking for?

class BaseClass(object):
    def __init__(self, name, date):
        self.name = name
        self.date = date

    def get_name_date(self):
        self.name_date = self.name +self.date

class UpperClass:
    def __init__(self, baseobject):
        self.baseobject = baseobject
        self.date_name = baseobject.date + baseobject.name

    def __getattr__(self, item):
        return getattr(self.baseobject, item)

o1 = BaseClass('thmei', 'may')
o2 = UpperClass(o1)

print(o1.date) # may
print(o2.date) # may
print(o2.date_name) # maythmei

Upvotes: 1

Related Questions