Course Content
In-Depth Python OOP
In-Depth Python OOP
Superclass
In Python, a superclass is a class that is inherited from by other classes. It serves as the parent class or base class, providing attributes and methods that can be inherited and utilized by its subclasses. They provide a way to define common functionality and characteristics that can be shared among multiple related classes.
The super()
function in Python is used to access and invoke methods or attributes from a superclass within a subclass. It provides a convenient way to delegate or call the superclass's implementation of a method. By using super()
, you can call a method defined in the parent class, even if the method has been overridden in the child class. This allows for code reuse and facilitates the extension or customization of the parent class's behavior.
The super()
function is typically used inside a subclass to call the parent class's methods. It takes two arguments: the subclass itself (usually self
) and the subclass instance (optional). When called without any arguments, super()
returns a temporary object of the superclass. You can then call methods or access attributes on this object using dot (.
). This provides a way to selectively override or extend the behavior of the parent class while still benefiting from its existing functionality.
class User: def __init__(self, username, password): self.username = username self.password = password class NewUser(User): def __init__(self, username, password, name, surname, age): super().__init__(username, password) self.name = name self.surname = surname self.age = age user = NewUser("user123", "secret_password", "John", "Johnson", 24) print(user.username) print(user.password) print(user.name) print(user.surname) print(user.age)
The provided code defines two classes: User
and NewUser
.
The User
class has a constructor method __init__()
that takes two parameters, username
and password
. The NewUser
class is a subclass of User
and extends it by adding additional attributes: name
, surname
, and age
.
The __init__()
method in the NewUser
class takes five parameters: username
, password
, name
, surname
, and age
. It calls the __init__()
method of the parent class (User
) using super().__init__(username, password)
to initialize the username
and password
attributes inherited from the User
class. It then sets the name
, surname
, and age
attributes using the provided values.
Note
You can use the
super()
function for other methods and attributes. Thesuper()
call methods from the Parent class and use Parent attributes. This allows us to extend parent methods.
One more example:
class User: role = "User" class Admin(User): role = "Admin" def info(self): print(self.role) print(super().role) admin = Admin() admin.info()
Note
The
super()
function is used by popular frameworks like Django.
Thanks for your feedback!