1

I have a super class which has some class attributes like:

class Config(object):    
    LENGTH = 1
    BREADTH = 3

Now ,I have created a subclass which will override the parent class attributes.

 class Sub1(Config):
     def __init__():
        self.LENGTH = 200
        self.BREADTH = 100
        self.AREA = self.LENGTH * self.BREADTH 

Now I need to write another subclass which will overwrite the values of the first sub class. Here, shall I inherit from the parent class Config or I can overwrite the values in the subclass itself and change it.

class Sub2(Sub1):
   self.AREA_UPDATED = self.AREA + 20

This is not working.

class Sub2(Config):
    self.LENGTH = "efg"
    self.BREADTH = 100
    self.AREA = self.LENGTH * self.BREADTH
    self.AREA_UPDATED = self.AREA + 20

This works. What am I doing conceptually wrong, is it that the parent class can be inherited only? Kindly advice.

Thanks

3 Answers 3

3

You can't use self in the class scope. You should just use the variable name simply like this:

class Sub2(Config):
    LENGTH = "efg"
    BREADTH = 100
    AREA = LENGTH * BREADTH
    AREA_UPDATED = AREA + 20

Because this way you will overwrite the class attributes not just the instance attributes as you did it in the __init__.

Inheriting from Sub1 you can do the same:

class Sub1(Config):
    LENGTH = 200
    BREADTH = 100
    AREA = LENGTH * BREADTH 

class Sub2(Sub1):
    AREA_UPDATED = Sub1.AREA + 20
Sign up to request clarification or add additional context in comments.

Comments

0

Change

class Sub2(Sub1):
   self.AREA_UPDATED = self.AREA + 20

to

class Sub2(Sub1):
  def __init__(self):
     self.AREA_UPDATED = self.AREA + 20

1 Comment

You should fix the __init__ like this: def __init__(self):. And on the class level you can't use self.
0

Correct me if I'm wrong, but wouldn't you use the breadth and width in the init to instantiate an object correctly? I mean just like this:

class Config(object):
   def __init__(self, width, breadth):
       self.width = width
       self.breadth = breadth
       self.area = width*breadth

taking the config as a superclass ( you could also use it as abstract base class, in which case my solution would be wrong).

And afterwards just properly let Sub1 inherit from Config like this:

class Sub1(Config):
  def __init__(self,width,breadth):
      Config.__init__(self,width,breadth)
      self.area = width * breadth

for sub2 you could obviously do the same. If you would want to know the updated area, you could just use setters for the attributes the class has.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.