Python Programming 2
Python Programming 2
Create a Class
To create a class, use the keyword class:
Create Object
Now we can use the class named MyClass to create objects:
The __init__() Function
The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.
All classes have a function called __init__(), which is always executed when the
class is being initiated.
If the __str__() function is not set, the string representation of the object is
returned:
Object Methods
Objects can also contain methods. Methods in objects are functions that belong
to the object.
It does not have to be named self , you can call it whatever you like, but it has
to be the first parameter of any function in the class:
Delete Objects
You can delete objects by using the del keyword:
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Now we have successfully added the __init__() function, and kept the
inheritance of the parent class, and we are ready to add functionality in
the __init__() function.
By using the super() function, you do not have to use the name of the parent
element, it will automatically inherit the methods and properties from its parent.
Add Properties
In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another
parameter in the __init__() function:
Add Methods
If you add a method in the child class with the same name as a function in the
parent class, the inheritance of the parent method will be overridden.