Arrays
There is no built-in functionality for arrays in python; just treat them exactly the same way as list: the same properties, same methods, same constructs.
Inheritance
Inheritance: the format is class child(parent) :
Use the pass keyword if you don't want to add any other properties or methods to the child class.
To keep parent inheritance, yet still create new child properties and methods, you need to call the __init__ twice!!
class child(parent):
def __init__(self, a, b, c):
parent.__init__(self, d, e, f)
In this case self in the parent call belongs to the child; it's not to be referring to the self in the actual parent class definition. Notice that no colon is used after the parent.
super() does the same thing as the parent's init call except you can leave out the self-referencing variable parameter in this case. Here also you're not using a trailing colon (:)
class child(parent):
def __init__(self, a, b, c):
super()__init__(d, e, f)
For some odd reason the parent parameter list must be repeated in the init call for explicit parent inheritance.
class child(parent):
def __init__(self, a, b, c):
parent.__init__() # incorrect syntax
Properties of the same name in the child will override the parents, same for methods.
Example #1 - hard coded parent property value remains unchanged in the child call
class Person:
def __init__(self, fname, lname, year):
self.firstname = fname
self.lastname = lname
self.yeargrad = 2100
def printname(self):
print(self.firstname, self.lastname. self.yeargrad)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname, year)
x = Student("John", "Quagliano", 1980)
print(x.yeargrad)
# result is:
2100
----------------------------------------
Example #2 - hard coded parent property value is overrdidden in the child call
and the child method of the exact same name as the parent's gets invoked instead.
class Person:
def __init__(self, fname, lname, year):
self.firstname = fname
self.lastname = lname
self.yeargrad = 2100
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname, year)
self.yeargrad = year
def printname(self): # same function name as for parent above
print("Welcome ", self.firstname, self.lastname, " to the class of ", self.yeargrad)
# notice that the python print built-in function automatically
# inserts spaces in between string arguments
x = Student("John", " Quagliano", 2019)
x.printname()
# result is:
Welcome John Quagliano to the class of 2019
No comments:
Post a Comment