Ajay Kumar
Ajay Kumar

Reputation: 1655

Python inherit the property of one class to another

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.

Upvotes: 1

Views: 540

Answers (3)

Abhijeetk431
Abhijeetk431

Reputation: 846

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

Upvotes: 0

MinasA1
MinasA1

Reputation: 164

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().

Upvotes: 1

Tom Karzes
Tom Karzes

Reputation: 24052

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.

Upvotes: 0

Related Questions