python class和def的区别_Python中classmethod和staticmethod的区别

今天来写一下装饰器classmethod和staticmethod这两个关键词。一般实现书写类结构体方法有三种,分别是实例方法(instancemethod)、classmethod、staticmethod。如果用一个代码总结展示就是下面这样。

class MyClass(object):

def instancemethod(self,parameters)

#可以操作实例和类

pass

@classmethod

def classmethod(cls):

#可以操作类,但不能操作实例

pass

@staticmethod

def staticmethod():

#不能操作实例和类

pass

classmethod装饰器

这个装饰器的存在是为了让我们可以创建类方法(这个类方法可以在函数内调用类对象,参数为cls。作用类似于self)

在实例方法中,self是类对象本身,通过作用self身上我们可以操作实例数据。@classmethod修饰的方法也有一个参数cls,但这个参数是非实例化的类本身。典型的类方法是这样使用的:

class Student(object):

def __init__(self, first_name, last_name):

self.first_name = first_name

self.last_name = last_name

scott = Student('Scott', 'Robinson')

classmethod是这样使用的

class Student(object):

def __init__(self, first_name, last_name):

self.first_name = first_name

self.last_name = last_name

@classmethod

def from_string(cls, name_str):

first_name, last_name = map(str, name_str.split(' '))

student = cls(first_name, last_name)

return student

scott = Student.from_string('Scott Robinson')

print(scott.firstname)

Scott

上面的例子很简单,但我们可以想象个更复杂的例子,你会发现这两个装饰器变的更有趣更有吸引力。假设我们写一个学生类Student,我们可以使用相同的策略来解析收到的数据。

class Student(object):

def __init__(self, first_name, last_name):

self.first_name = first_name

self.last_name = last_name

@classmethod

def from_string(cls, name_str):

first_name, last_name = map(str, name_str.split(' '))

student = cls(first_name, last_name)

return student

@classmethod

def from_json(cls, json_obj):

# parse json...

return student

@classmethod

def from_pickle(cls, pickle_file):

# load pickle file...

return student

staticmethod装饰器

staticmethod装饰器跟classmethod装饰器类似,都作用于类结构体内。

class Student(object):

@staticmethod

def is_full_name(name_str):

names = name_str.split(' ')

return len(names) > 1

Student.is_full_name('Scott Robinson') # True

Student.is_full_name('Scott')

但是staticmethod装饰的函数没有cls/self参数,因此其装饰的方法与类结构数据关系不太紧密,所以平常我们在实例化类之后,在实例上调用staticmethod修饰的方法,并不能操作实例数据。在实例上看,staticmethod装饰的方法,更像是一个函数,而不是方法。

class Student(object):

def __init__(self, first_name, last_name):

self.first_name = first_name

self.last_name = last_name

@staticmethod

def is_full_name(name_str):

names = name_str.split(' ')

return len(names) > 1

scott = Student('Scott', 'Robinson')

#这样运行没错,但还不如写一个函数,而不是类内的方法。

scott.is_full_name('Scott Robinson')

staticmethod装饰的方法(函数),用处还是有的,可以被类内的其他方法调用。

classmethod与staticmethod

这两个方法装饰器之间确实有一个主要区别,您可能注意到在上面的部分@classmethod方法有一个cls参数,而@staticmethod方法没有。

这个cls参数是我们讨论的类对象,它允许@classmethod方法轻松实例化类。 @staticmethod方法中缺少这个cls参数使得它们成为传统意义上的静态方法。它们的主要目的是包含关于类的逻辑,但这个逻辑不应该需要特定的类实例数据。

更实战一点的例子

class ClassGrades(object):

def __init__(self, grades):

self.grades = grades

@classmethod

def from_csv(cls, grade_csv_str):

grades = map(int, grade_csv_str.split(', '))

#调用类方法validate

cls.validate(grades)

return cls(grades)

@staticmethod

def validate(grades):

for g in grades:

if g < 0 or g > 100:

raise Exception()

try:

#使用有效数据

class_grades_valid = ClassGrades.from_csv('90, 80, 85, 94, 70')

print('Got grades:', class_grades_valid.grades)

#无效数据,应该会报错

class_grades_invalid = ClassGrades.from_csv('92, -15, 99, 101, 77, 65, 100')

print(class_grades_invalid.grades)

except:

print('Invalid!')

Got grades: [90, 80, 85, 94, 70]

Invalid!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值