bcbeer 2017-07-15
定义:
静态函数(@staticmethod): 即静态方法,主要处理与这个类的逻辑关联, 如验证数据;
类函数(@classmethod):即类方法, 更关注于从类中调用方法, 而不是在实例中调用方法, 如构造重载;
成员函数: 实例的方法, 只能通过实例进行调用;
class Foo(object):
"""类方法的三种语法形式"""
def instance_method(self):
print("是类{}的实例方法,只能被实例对象调用".format(Foo))
@staticmethod
def static_method():
print("是静态方法")
@classmethod
def class_method(cls):
print("是类方法")
foo = Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print('----------------')
Foo.static_method()
Foo.class_method()由此看一看出来,
实例方法只能被实例对象调用,静态方法(由@staticmethod装饰的方法)、类方法(由@classmethod装饰的方法),可以被类或类的实例对象调用。
实例方法,第一个参数必须要默认传实例对象。
静态方法,参数没有要求。
类方法,第一个参数必须要默认传类。
他们是怎么应用的;
比如日期的方法, 可以通过实例化(__init__)进行数据输出;
可以通过类方法(@classmethod)进行数据转换;
可以通过静态方法(@staticmethod)进行数据验证;
例子
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()) //12*11*2014
print(date2.display()) //11*13*2014
print(date2.is_date_valid('11-13-2014')) //False
print(Date.is_date_valid('11-13-2014')) //False