标签:
通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法呢?其实不难理解,普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法
#静态方法
class Schoolmate(object):
def __init__(self, name):
self.name = name
@staticmethod # 把eat方法变为静态方法
def eat(self):
print("%s is eating" % self.name)
p= Schoolmate("LianZhiLei")
p.eat()
# Traceback (most recent call last):
# File "C:/Users/L/PycharmProjects/s14/class/Day7/staticmothod.py", line 16, in <module>
# p.eat()
#TypeError: eat() missing 1 required positional argument: ‘self‘
上面的调用会出以下错误,说是eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。
想让上面的代码可以正常工作有两种办法
#静态方法
class Schoolmate(object):
def __init__(self, name):
self.name = name
@staticmethod # 把eat方法变为静态方法
def eat(self):
print("%s is eating" % self.name)
p= Schoolmate("LianZhiLei")
p.eat(p)
#LianZhiLei is eating
#静态方法
class Schoolmate(object):
def __init__(self, name):
self.name = name
@staticmethod # 把eat方法变为静态方法
def eat():
print("is eating")
p= Schoolmate("LianZhiLei")
p.eat()
#is eating
类方法顾名思义跟类有关,类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量
#类方法
class Schoolmate(object):
def __init__(self, name):
self.name = name
@classmethod # 把eat方法变为类方法
def eat(self):
print("%s is eating" % self.name)
p= Schoolmate("LianZhiLei")
p.eat()
# Traceback (most recent call last):
# File "C:/Users/L/PycharmProjects/s14/class/Day7/classmothod.py", line 15, in <module>
# p.eat()
# File "C:/Users/L/PycharmProjects/s14/class/Day7/classmothod.py", line 12, in eat
# print("%s is eating" % self.name)
# AttributeError: type object ‘Schoolmate‘ has no attribute ‘name‘
执行报错如下,说schoolmat没有name属性,这是因为name是个实例变量,类方法是不能访问实例变量的,只能访问类变量
#类方法
class Schoolmate(object):
name = ("Schoolmat的类变量")
def __init__(self, name):
self.name = name
@classmethod # 把eat方法变为类方法
def eat(self):
print("%s is eating" % self.name)
p= Schoolmate("LianZhiLei")
p.eat()
# Schoolmat的类变量 is eating
此时可以定义一个类变量,变量名为name即可解决
属性方法的作用就是通过@property把一个方法变成一个静态属性,这个蛮有用的,后面课程会涉及到,先看代码
标签:
原文地址:http://www.cnblogs.com/lianzhilei/p/5838821.html