Python学习之路11——面向对象进阶

一、静态方法

   通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法呢?

   其实不难理解,普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量。

      但静态方法是不可以访问实例变量或类变量的,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法;

   静态方法不可访问实例变量跟类变量,内部其他函数可通过self.静态方法执行,需要实例化

 1 #!/user/bin/env ptyhon
 2 # -*- coding:utf-8 -*-
 3 # Author: VisonWong
 4 
 5 
 6 # 静态方法
 7 class Schoolmate(object):
 8     def __init__(self, name):
 9         self.name = name
10 
11     @staticmethod  # 把eat方法变为静态方法
12     def eat(self):
13         print("%s is eating" % self.name)
14 
15 
16 p = Schoolmate("VisonWong")
17 p.eat()
18 
19 
20 # Traceback (most recent call last):
21 #   File "E:/Python/PythonLearing/class/静态方法.py", line 17, in <module>
22 #     p.eat()
23 # TypeError: eat() missing 1 required positional argument: 'self'

   上面的调用会出以下错误,说是eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。

猜你喜欢

转载自www.cnblogs.com/visonwong/p/9144653.html