1

I have three different class's and some variables in it

class A(object):
    a = "Hello"
    b = "World"

class B(object):
    a = "Hello"
    b = "World"

class C(object):
    a = "Hello"
    b = "World"

Where a = "Hello" and b = "World" is common to all class's, how can I declare these variables as a global class and Inherit the properties to these tables.

I Tried in this way, but am not able to get the solution.

class G(object):
    a = "Hello"
    b = "World"

class A(object, G):
    pass

Here I'm trying to inherit the whole property of the class. Please help me to solve this thanks in advance.

Ajay Kumar
  • 1,595
  • 3
  • 20
  • 36

3 Answers3

1
class A(object):
    a = "Hello"
    b = "World"

class B(A):
  something

class C(B):
  something

c = C()
print(c.a,c.b)

You don't have to re-declare a and b each time or else why would you inherit in the first place. If you declare them you basically are overwriting the parent's variable with the child's. If you do that you can call the parent's one with super().

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
MinasA1
  • 164
  • 7
0

Define class A as:

class A(G):
    pass

The problem with repeating the base class object is that it creates a base class resolution conflict, since A was inheriting it twice: Once directly, and once indirectly through class G.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

This is how you do it. Please let know in comments if there is something that you don't understand, or if I am doing anything wrong.

class A(object):
    a = "Hello"
    b = "World"

class B(A):
    pass

class C(B):
    pass

c = C()
print(c.a,c.b)

Prints Hello World

Abhijeetk431
  • 847
  • 1
  • 8
  • 18
  • Thanks @Abhijeet, I got solution from your answer, thanks a lot – Ajay Kumar Nov 22 '17 at 07:34
  • 2
    No need to declare a and b again with same values. You inherit them already! only reason to declare again if you want to store new values for each class but still you can call the parent's Class value with super() – MinasA1 Nov 22 '17 at 07:36
  • This answer is quite misleading. This is a terrible example of how to do inheritance. – Jean-François Corbett Nov 22 '17 at 07:53
  • Edited the answer. Sorry for declaring variables again. This is what I intended to do but removing extra declarations slipped out of my mind. – Abhijeetk431 Nov 22 '17 at 08:36