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
2
3
4
5
6
7
class Pet(object):
def my_method(self):
print("I am a Cat")
cat = Pet()
cat.my_method()

>> I am a Cat

If we want object accept arguments, like

1
cat = Pet('Cat')

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
2
3
4
5
6
7
8
9
class Pet:
def __init__(self, name):
self.name = name
def my_method(self):
print(f"I am a {self.name}")
cat = Pet("Cat")
cat.my_method()

>> I am a Cat

##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
2
3
4
5
6
7
8
9
10
11
12
class Student:
def __init__(self, name, gender, score):
self.name = name
self.gender = gender
self.score = score
def grade(self):
if self.score>=60:
print(f'{self.name} passes the final exam.')
else:
print(f'{self.name} fails the final exam.')

student1 = Student(name = 'Arwen', gender = 'female', score = 80)

##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
student1.grade()

Arwen passes the final exam.

1
2
3
student1.gender

>> 'female'

We can use other magic method in python, such as __dict__. [4]

For class “Student”, __dict__ returns all the attributes in the class.

1
2
3
4
5
6
7
8
Student.__dict__

>> mappingproxy({'__module__': '__main__',
>> '__init__': <function __main__.Student.__init__(self, name, gender, score)>,
>> 'grade': <function __main__.Student.grade(self)>,
>> '__dict__': <attribute '__dict__' of 'Student' objects>,
>> '__weakref__': <attribute '__weakref__' of 'Student' objects>,
>> '__doc__': None})

For object “student1”, __dict__ returns all the attributes of the object. The method in the class will not be included.

1
2
3
student1.__dict

>> {'name': 'Arwen', 'gender': 'female', 'score': 80}


Python - Method
http://arwenzhou.github.io/2022/08/22/Python-Method/
Author
Arwen
Posted on
August 22, 2022
Licensed under