Home > Back-end >  Can a subclass access attributes from its superclass in Python?
Can a subclass access attributes from its superclass in Python?

Time:03-14

In Python, is it possible for a subclass access attributes from its superclass? Below is a short example code that I would like to make work.

class A:
    def __init__(self, some_value):
        self.some_property_A = some_value
        
    class B:
        def __init__(self):
            self.some_property_B = 0
            if some_property_A == 1:     # <-------- How can I make this line work?
                self.some_property_B = 1

Thanks for you help in advance.

CodePudding user response:

Your Class B is not your subclass.

Here is the example:

# superclass
class Person():
    def __init__(self, per_name, per_age):
        self.name = per_name
        self.age = per_age
 
# subclass      
class Employee(Person):
    def __init__(self, emp_name, emp_age, emp_salary):
        self.salary = emp_salary
        Person.__init__(self, emp_name, emp_age)
        
emp = Employee("John", 20, 8000)  # creating object of superclass
 
print("name:", emp.name, "age:", emp.age, "salary:", emp.salary)

This is how you can use variables of Superclass. For more information visit:

https://www.codesdope.com/course/python-subclass-of-a-class/#:~:text=All the attributes and methods,and methods of the superclass.

  • Related