Home > Software engineering >  How do I access an attribute from a parent class in Python?
How do I access an attribute from a parent class in Python?

Time:05-18

This doesn't work:

class parent:
    a=1
    class child:
        b=a 1

nor does

class parent:
    a=1
    class child:
        b=parent.a 1

nor does

class parent:
    a=1
    class child:
        b=self.a 1

nor does

class parent:
    a=1
    class child:
        b=super().a 1

What do I do? I've heard that Stack Overflow can be quite toxic, but I'm hoping it's not true. Please understand that I'm new here.

CodePudding user response:

class Parent():
    def __init__(self):
        self.a = 1

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
        self.b = self.a  1
        
child_class = Child()
print(child_class.b)

Maybe something like this.

CodePudding user response:

The proper way to create a child class is like this:

class parent():
    a = 1

# child class inherits attributes from parent like this
class child(parent):
    b = 2

# so when you instantiate an object of class child...
child_object = child()

# ... you can access its parent's attributes directly like this:
print(child_object.a   child_object.b)

If you want to access the parent's attribute inside a method, you can do like this:

class child(parent):
    b = 2

    def sum_with_parent(self):
        # you can either use self.a to access the parent attribute,
        # since 'class child(parent):' made the proper inheritance
        sum1 = self.b   self.a

        # or you can use the super().a, but bear in mind that 'super()'
        # is actually creating a fresh instance of parent
        # that is, it's calling __init__ from parent
        sum2 = self.b   super().a

        return sum1 == sum2 #this will return true

CodePudding user response:

Welcome to Stack Overflow. It seems like you don’t quite understand what inheritance is. Here is a quick “deep” dive.

What is inheritance in OOP?

Inheritance is a fundamental concept in object oriented programming. It is when you provide a base or super class for another class. The super class usually contains functionality that will apply, or be useful, to any instance of the classes deriving from it. It prevents you from having to reimplement things.

Inheritance in Python

In Python, a class deriving from another class automatically is able to access methods and attributes defined in super class, through the super() function:

class Foo:
    def bar(self):
        print("bar")
        
class Bar(Foo):
    def bar(self):
        super().bar()
        
b = Bar()
b.bar() # bar

Even if we use the convention for showing some method or attribute is private, which is prefixing with an underscore, Python doesn’t enforce this and we can still access it:

class Foo:
    def _bar(self):
        print("bar")
        
class Bar(Foo):
    def bar(self):
        super()._bar()
        
b = Bar()
b.bar() # bar

Inheritance in Other OO Languages

In other object oriented languages like C#, there are access modifiers. Marking a method with public means it has no restrictions to what can access it. It can be accessed by:

  • All code in the assembly it was defined in
  • All code in any assemblies referencing the assembly where it was defined

But, C# gives us the option to multiple other access modifiers, including private. Marking something as prívate means it can only be accessed by the code in the same class, or struct, it was defined in:

class Foo 
{
    private string _x = "Foo";
}

static void Main()
{
    var foo = new Foo();

    Console.WriteLine(foo._x); // compile time error
}

But, restricted members can be indirectly accessed through a public API:


class Foo 
{
    private string _x = "Foo";

    public string AccessPrivate()
    {
        return _x;
    }
}

static void Main()
{
    var foo = new Foo();

    Console.WriteLine(foo.AccessPrivate());
}

Python’s super() function

mCoding on YouTube has a great video explaining how super() works

Simply, super() will give you access to methods in a superclass, from subclasses that inherit from it. Calling it actually returns a temporary object of the superclass, letting you access its methods and attributes.

The official Python documentation on super() says:

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.

Single inheritance with super()

super() is relatively simple with single inheritance, as shown in the Inheritance in Python section.

You commonly see it used in the __init__ method for calling the superclass’s initializer with arguments supplied by the initializer of the subclass:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

class Square(Rectangle):
    def __init__(self, length):
        super().__init__(length, length)

We define a class Rectangle whose initializer takes a length and width parameter. The length and width of a rectangle will be different. Next, we define a class Square, deriving from Rectangle. This makes sense because all squares are rectangles. Rectangles are not squares though because they don’t have equal length sides, but a square’s dimensions will always be the same. We pass length to Square’s __init__. This length parameter is then passed to the constructor of the superclass as the argument for both length and width.

super() is also good for extending the functionality of an inherited method.

I hope this message helped explain a bit on what inheritance is and accessing attributes/methods from the parent class, in the subclass.

CodePudding user response:

Your question does not reflect properly in your code. As per inheritance of classes you inherit from a parent class. But in your code you are trying to call outerclass from an inner class.

One solution might be like this (According to your question):

class Parent:
    a = 1

class Child(Parent):
    b = Parent.a   1


parent = Parent()
child = Child()

print(parent.a) # output: 1
print(child.b) # output: 2

But if you really want to access outer class from inner class then you can visit
How to access outer class from an inner class? (according to your code)

  • Related