---
title: Python Class Method Introduction
tags: Python, instantmethod, classmethod, staticmethod
description: Python class method introduction
---
# Python Class Methid Introduction
python class 有三種方法, instant method, static method, and class method. 在以下 class 類別中分別建立三種方法,
```
class Test(object):
def __init__(self):
self.param = 1
def t1(self, n):
print("get param: %s" %(str(self.param)))
print("self:", self)
@classmethod
def t2(cls, n):
print("get param: %s" %(str(cls.param)))
print("cls:", cls)
@staticmethod
def t3(n):
pass
t = Test()
t.t1(1) # self: <__main__.A object at 0x000001E596E41A90>
Test.t2(1) # cls: <class '__main__.A'>
Test.t3(1)
```
### instant method
必須要把 class 實例化才能呼叫 class 內部函數,其中 t1 裡 self 指向的是整個 class 實體化過後的物件位址。
補充: 實例化 t 後其物件位址為,直接 call t.t1(1)可以得到其物件位址0x000001E596E41A90,而如果沒有實例化直接 call 則必須已經實例化的物件位址傳去self的地方,如Test(t, 1)部分。
```
t = Test()
t.t1(1) # self: <__main__.A object at 0x000001E596E41A90>
Test(t, 1) # self: <__main__.A object at 0x000001E596E41A90>
```
### class method
不需要實例化 class 物件即可以使用內部 function,透過 cls 可以取得 class 的類,因此可以調用 class 內部函數以及參數。
```
print(A.m2)
<bound method A.m2 of <class '__main__.A'>>
print(a.m2)
<bound method A.m2 of <class '__main__.A'>>
```
#### 使用情景
以下使用情景讓 class 在 init 時更有彈性。
````
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
person = Person('Adam', 19)
person.display()
person1 = Person.fromBirthYear('John', 1985)
person1.display()
#Output
Adam's age is: 19
John's age is: 31
````
### staticmethod
不需要實例化 class 物件即可以使用內部 function,但無法 get 到 class 內部函數以及參數,以下些可以調用 staticmethod,其函數指向同一個位址,因此大量調用時可以節省記憶體空間。
```
print(Test.t3)
<function A.m3 at 0x000002BF7FF9A840>
print(t.t3)
<function A.m3 at 0x000002BF7FF9A840>
```
#### 使用情景
當 class 內 function 不須與內部共用,因此大量調用時可以節省記憶體空間。
---
## 參考
* https://zhuanlan.zhihu.com/p/28010894
* https://ji3g4zo6qi6.medium.com/python-tips-5d36df9f6ad5
## Thank you! :dash:
You can find me on
- GitHub: https://github.com/shaung08
- Email: a2369875@gmail.com