super() code example
Example 1: python super
# It's kinda hard to explain this just by code.
# So I'll provide a link to a pretty good explanation of it.
https://www.pythonforbeginners.com/super/working-python-super-function
Example 2: python super
# The super() function lets you run a parent class function inside the child class.
class Parent(object):
def __init__(self, age):
self.age = age
def func(self):
print(f"Hi, my age is {self.age}!")
class Child(Parent):
def __init__(self, age):
# Here is where I can use the super to run the parent class __init__ function to set the childs' name
super().__init__(age)
dad = Parent(36)
kid = Child(8)
dad.func()
kid.func() # The kid inherits it from the dad, so I could run it like that too
Example 3: python super
class Square(Rectangle):
def __init__(self, length):
super().__init__(length, length)
Example 4: super in javascirpt
class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
get area() {
return this.height * this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Rectangle {
constructor(length) {
this.height;
super(length, length);
this.name = 'Square';
}
}
Example 5: what is the purpose of super keyword in python
class Parent:
def __init__(self, txt):
self.message = txt
def printmessage(self):
print(self.message)
class Child(Parent):
def __init__(self, txt):
super().__init__(txt)
x = Child("Hello, and welcome!")
x.printmessage()