How can I get self. variable from a parent class?

Viewed 555

This might be very bad example, but I'm new with OOP, I'm trying to get the same self.number list that I have created inside random_number without calling random.randint again. but self.number is empty when I'm calling inside class B, what can be the right approach?

import random
class A:
    def __init__(self):
        self.number = []

    def random_number(self):
        for i in range(4):
            self.number.append(random.randint(1, 100))
            random.randint(1, 100)

        print("from class A", self.number)

class B(A):
    def __init__(self):
        super().__init__()
        # something here

    def get_name(self):
        A().random_number()
        print("from class B", self.number)

B().get_name()
1 Answers

Doing A().random_number() will create a new instance of class A then call the random_number method of that newly created instance, and that's obviously not what you want.

You need to access the method from the instance of class B, and since you are extending the class A to create class B, you can use the parent class methods directly into the child class i.e. self.random_number:

import random
class A:
    def __init__(self):
        self.number = []

    def random_number(self):
        for i in range(4):
            self.number.append(random.randint(1, 100))
            random.randint(1, 100)

        print("from class A", self.number)

class B(A):
    def __init__(self):
        super().__init__()
        # something here

    def get_name(self):
        # A().random_number()
        self.random_number()   #<--- calling self.random_number()
        print("from class B", self.number)

B().get_name()

OUTPUT:

from class A [16, 24, 100, 47]
from class B [16, 24, 100, 47]
Related