Skip to content

Access Specifiers

Parent Class Constructor through Child Object:
In Python, you can call the constructor of a parent class from the constructor of a child class using the super() function. This allows you to invoke the parent class’s constructor to initialize the inherited attributes. Here’s how you can do it:

🐍
filename.py
#Example

class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)  # Call the constructor of the parent class
        self.age = age

child_obj = Child("Alice", 5)

print(child_obj.name)  # Output: "Alice"
print(child_obj.age)   # Output: 5

In the example above, the Child class inherits from the Parent class. In the Child class’s constructor, super().__init__(name) is used to call the constructor of the parent class (Parent). This ensures that the name attribute of the parent class is initialized correctly.

 

By using super(), you can access and call methods or constructors of the parent class within the child class, allowing you to reuse and extend the behavior of the parent class in the child class.

 

It is the responsibility of the constructor of child class to call the constructor of its parent class at the time of the declaration of the child class object.

 

It has to use super().__init__() to make a call to super class constructor.

🐍
filename.py
#Example
class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)  # Call the constructor of the parent class
        self.age = age

child_obj = Child("Alice", 5)

print(child_obj.name)  # Output: "Alice"
print(child_obj.age)   # Output: 5
🐍
filename.py
#Example
class Parent:
    def __init__(self):
        self.x=10
        return

    def showParent(self):
        print("x=",self.x)
        return

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()
        self.y=20
        return

    def showChild(self):
        print("y=",self.y)
        return


#main program
obj = Child()
obj.showParent()
obj.showChild()

Practice:
1. Write a Python program to create a Parent class with a constructor that prints “Parent constructor called”. Create a Child class that inherits from Parent. Create an object of the Child class and observe if the parent constructor is called.

 

2. Write a Python program where the Parent class constructor takes a name as a parameter and prints “Parent name is <name>”. The Child class should call the parent constructor using super(). Create a Child object with the name “Rahul” and print the message.

 

3. Write a Python program with a Parent class having a constructor that initializes self.value = 100. The Child class should call the parent constructor and also initialize self.child_value = 200. Create a child object and print both value and child_value.

 

4. Write a Python program where the Parent class constructor prints “Initializing Parent”. The Child class has its own constructor which calls the parent constructor using super(), then prints “Initializing Child”. Create an object of Child and show the output.

 

5. Write a Python program to demonstrate multi-level inheritance.

Class Grandparent should have a constructor that prints “Grandparent Constructor”.
Class Parent should inherit Grandparent and its constructor should print “Parent Constructor” after calling Grandparent’s constructor.
Class Child should inherit Parent and its constructor should print “Child Constructor” after calling Parent’s constructor.
Create an object of the Child class and observe the output.

Access Specifiers in python
In Python, there are no access specifiers like “public,” “private,” or “protected” as you might find in some other programming languages. Python follows a principle known as “data hiding,” but it doesn’t enforce strict access control like languages such as Java or C++. However, you can achieve access control and encapsulation through naming conventions and documentation. Here’s how it works:

 

Public members: In Python, class attributes and methods that have names not starting with underscore are considered public and can be accessed from outside the class. These members are part of the public API of the class.

🐍
filename.py
#Example

class MyClass:
    def publicMethod(self):
        pass

    publicAttribute = 42

Protected members: Although there is no strict enforcement of protected members, developers use a single underscore prefix (e.g., _my_variable) to indicate that an attribute or method is intended for internal use or should be considered “protected.” It’s a signal to other developers that these members are not part of the public API but can still be accessed if needed.

🐍
filename.py
#Example

class MyClass:
    def _protected_method(self):
        pass

    _protected_attribute = 42

Private members: Similar to protected members, there are no strict access controls, but a double underscore prefix (e.g., __my_variable) is used to indicate “private” members. These names undergo name mangling, making it more difficult to access them from outside the class. However, they can still be accessed if you know the name mangling rules.

🐍
filename.py
#Example
class MyClass:
    def __init__(self):
        self.__private_attribute = 42

    def __private_method(self):
        pass

Remember that these naming conventions and access “control” mechanisms are more about convention and readability rather than strict access control. Python trusts developers to follow these conventions but doesn’t prevent you from accessing any class member directly. It’s a “we’re all consenting adults here” approach, which means that it’s essential to follow best practices and respect these conventions when working on Python projects for code readability and maintainability.

🐍
filename.py
#Example
class sample:
    def __init__(self):
        self.var1=int()
        self._var2=int()
        self.__var3=int()
    
    def show(self):
        print("Var1=",self.var1)
        print("Var2=",self._var2)
        print("Var3=",self.__var3)

obj=sample()
obj.show()
print(obj.var1)
print(obj._var2)
print(obj.__var3) #shows error 

Practice:
1. Write a Python program to create a class Student with a public data member name. Define a method to display the name. Create an object of the class and access the name variable directly and through the method.


2. Write a Python program to demonstrate the use of a protected member in a class.
Create a class Employee with a protected variable _salary.
Create a subclass Manager that inherits Employee and accesses the protected member.
Print the salary using both base class and derived class objects.


3. Write a Python program to create a class Account with a private data member __balance.
Provide a public method get_balance() to return the balance.
Try to access the __balance variable directly and explain what happens.


4. Write a Python program to create a class Bank with a private method __secret_code().
Call this private method using name mangling syntax from outside the class.
Show how private methods can still be accessed in Python (though not recommended).


5. Write a Python program to create a base class Person with:

a public member name,

a protected member _age,

a private member __aadhar.

Create a derived class Citizen and try accessing all three members inside the derived class.
Also, try to access them using an object of the derived class and explain which ones are accessible.