Python - Method
Method
What is method?
A Python method is a label that you can call on an object; it is a piece of code to execute on that object. [1]
The difference between method and function
A method in python is similar to a function, except it is associated with object/classes. There are two major differences. [2]
The method is implicitly used for an object for which it is called.
The method is accessible to data that is contained within the class.
1 |
|
If we want object accept arguments, like
1 |
|
We need __init__
method. Otherwise, the program will report error as “TypeError: object() takes no arguments.”
The __init__
method lets us assign a value for the “self.name” variable in our class. Here the __init__
is one way to implement magic method in python.
1 |
|
##Class
A Class
is like an object constructor, or a “blueprint” for creating objects. [3]
It has all the properties mentioned in the plan, and the corresponding object
behaves as the plan.
We can take a the class ‘Student’ as example. It contains properties like name, gender, and grade.
1 |
|
##Object
A Python object
is an instance of a class
. It can have properties and behavior accordingly. We just created the class “Student” and an object “student1”. So we can access the method and the attribute of “student1”:
1 |
|
Arwen passes the final exam.
1 |
|
We can use other magic method in python, such as __dict__
. [4]
For class “Student”, __dict__
returns all the attributes in the class.
1 |
|
For object “student1”, __dict__
returns all the attributes of the object. The method in the class will not be included.
1 |
|