Python - 靜態函數(staticmethod), 類函數(classmethod), 成員函數 區別(完全解析)
阿新 • • 發佈:2017-11-06
assm self log -i 邏輯 int -a spa 構造
原文地址:http://blog.csdn.net/caroline_wendy/article/details/23383995
靜態函數(staticmethod), 類函數(classmethod), 成員函數的區別(完全解析)
定義:
靜態函數(@staticmethod): 即靜態方法,主要處理與這個類的邏輯關聯, 如驗證數據;
類函數(@classmethod):即類方法, 更關註於從類中調用方法, 而不是在實例中調用方法, 如構造重載;
成員函數: 實例的方法, 只能通過實例進行調用;
代碼:
# -*- coding: utf-8 -*- #eclipse pydev, python 3.3#by C.L.Wang class A(object): _g = 1 def foo(self,x): print(‘executing foo(%s,%s)‘%(self,x)) @classmethod def class_foo(cls,x): print(‘executing class_foo(%s,%s)‘%(cls,x)) @staticmethod def static_foo(x): print(‘executing static_foo(%s)‘%x) a = A() a.foo(1) a.class_foo(1) A.class_foo(1) a.static_foo(1) A.static_foo(‘hi‘) print(a.foo) print(a.class_foo) print(a.static_foo)
輸出:
executing foo(<__main__.A object at 0x01E2E1B0>,1) executing class_foo(<class ‘__main__.A‘>,1) executing class_foo(<class ‘__main__.A‘>,1) executing static_foo(1) executing static_foo(hi) <bound method A.foo of <__main__.A object at 0x01E2E1B0>> <bound method type.class_foo of <class ‘__main__.A‘>> <function A.static_foo at 0x01E7E618>
具體應用:
比如日期的方法, 可以通過實例化(__init__)進行數據輸出;
可以通過類方法(@classmethod)進行數據轉換;
可以通過靜態方法(@staticmethod)進行數據驗證;
代碼:
- # -*- coding: utf-8 -*-
- #eclipse pydev, python 3.3
- #by C.L.Wang
- class Date(object):
- day = 0
- month = 0
- year = 0
- def __init__(self, day=0, month=0, year=0):
- self.day = day
- self.month = month
- self.year = year
- def display(self):
- return "{0}*{1}*{2}".format(self.day, self.month, self.year)
- @classmethod
- def from_string(cls, date_as_string):
- day, month, year = map(int, date_as_string.split(‘-‘))
- date1 = cls(day, month, year)
- return date1
- @staticmethod
- def is_date_valid(date_as_string):
- day, month, year = map(int, date_as_string.split(‘-‘))
- return day <= 31 and month <= 12 and year <= 3999
- date1 = Date(‘12‘, ‘11‘, ‘2014‘)
- date2 = Date.from_string(‘11-13-2014‘)
- print(date1.display())
- print(date2.display())
- print(date2.is_date_valid(‘11-13-2014‘))
- print(Date.is_date_valid(‘11-13-2014‘))
輸出:
12*11*2014
11*13*2014
False
False
參考:
http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner
http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python
Python - 靜態函數(staticmethod), 類函數(classmethod), 成員函數 區別(完全解析)