Python super()
The super() function returns a temporary object that allows a given class to inherit the methods and properties of a parent or sibling class.
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 CoursesIncludes 6 Courses
- With Professional CertificationWith Professional Certification
- Beginner Friendly.75 hours75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With CertificateWith Certificate
- Beginner Friendly.24 hours24 hours
Syntax
super(type, obj)
The type parameter specifies the type object of the parent class. The obj is optional and is an instance, or subtype, of the class type.
Inside Class Definition
When used inside a class definition, the super() function can be used with zero arguments since the given class inherits from a parent class:
class A():
method(self, arg):
#Method code starts here
class B(A):
method(self, arg):
super().method(arg)
#Method code starts here
The super() function allows the child class B to access the .method() of parent class A.
Outside Class Definition
The following syntax can be applied inside and outside of a class definition:
class B(A):
method(self, arg):
super().method(arg)
#Method code starts here
instance_of_b = B()
super(B, instance_of_b).method()
The super() function accepts the class type B along with an instance_of_b variable to direct the lookup search for a .method() in the nearest parent class.
Codebyte Example
In the following example, both syntaxes of super() are implemented in the classes Python and Java to access the intro() method of the parent ProgramLanguage class:
Visit usVisit usCodeHide codeOutputHide outputCopy to your clipboard
All contributors
- Preview: Anonymous contributor 2 total contributions
- Anonymous contributor
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 CoursesIncludes 6 Courses
- With Professional CertificationWith Professional Certification
- Beginner Friendly.75 hours75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With CertificateWith Certificate
- Beginner Friendly.24 hours24 hours
