简述python类方法和静态方法_Python类方法和静态方法

解释一: 静态函数, 类函数, 成员函数的区别?

解答:

定义:

静态函数(@staticmethod): 即静态方法,主要处理与这个类的逻辑关联;

类函数(@classmethod): 即类方法, 更关注于从类中调用方法, 而不是在实例中调用方法, 可以用作方法重载, 传入参数cls;

成员函数: 实例的方法, 只能通过实例进行调用;

具体应用:

日期的方法, 可以通过实例化(init)进行数据输出, 传入参数self;

可以通过类的方法(@classmethod)进行数据转换, 传入参数cls;

可以通过静态方法(@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())

print(date2.display())

print(date2.is_date_valid('11-13-2014'))

print(Date.is_date_valid('11-13-2014'))

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).

总结:简单来说就是两个函数的逻辑都和类有关,只不过classmethod需要和类交互,staticmethod不需要和类交互

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值