Classes Flashcards
Constructor
The constructor is a method that is called when an object is created
_init__
Instance variable
Is defined at the instance level. It can be changed across the instances
Class variable
Defined at the class level and is not expected to change
How to call class variable
Object.class
How to change class variable
Class.class = change
Types of instance methods
Accessor and mutator methods
How do you define class variable in the function
With a decorator @classmethod
And pass cls as an attribute in the function
How to define static method
With a decorator @staticmethod
What is inheritance
Is a mechanism that allows a class to inherit properties and behaviors from another class
Multiple inheritance
Child class passes multiple parent classes as an attribute.
class C(A,B):
How does constructor is being called with inheritance
- If there is no constructor in child class, parent constrictor method is being called
- If there is a contractor in child class, child class constructor is being called
- To call parent constructor with child constructor:
super().__init__()
Types of polymorphism
- Duck typing
- operator overloading
- method overloading
- method overriding
What is polymorphism
As the word suggests, ‘poly’ means ‘many’ and ‘morph’ points at ‘forms’; thus, polymorphism as a whole would mean ‘a property of having many forms.
One function is doing many different things
Duck typing
A way of programming in which an object passed into a function or method supports all method signatures and attributes expected of that object at run time.
You do not check types at all. Instead, you check for the presence of a given method or attribute
Operator overloading
Ability to define or redefine the behavior of build it operators(+,-,*,/<,>, etc) for custom objects or classes