V
V
Vampre2018-02-13 15:03:38
Python
Vampre, 2018-02-13 15:03:38

How to make a separate class attribute for each subclass?

Depends on a simple task: let's say there is a Super class with a class attribute a=5 b and a get_sum method:

class Super:
    a = 5
    def get_sum(self):
        self.b = (?).a + 5

From this class we create a subclass SubClass (Super) with its own variable a:
class SubClass(Super):
    a = 8

How to make it so that when calling SubClass.get_sum(), it is considered exactly 8 + 5? That is, let's say we need to create several subclasses that will call the get_sum method, but at the same time they should take only their atr. "a".

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Azim Kurt, 2018-02-13
@Vampre

class Super:
  a = 1
  def get_sum(self):
    print(self.a + 5)
    
class SubClass(Super):
  a = 8
  
o = SubClass()
o.get_sum()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question