Python中的装饰器

2018-12-19  本文已影响0人  VanJordan

A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.

A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how dict.fromkeys(), a classmethod, returns an instance of the subclass when called on a subclass:

class room:
    tag=1
    def __init__(self, name,length,width,height):
        self.name=name
        self.length=length
        self.width=width
        self.height=height
    @property  #通过类提供的property对求面积的函数进行封装
    def square(self):
        s=self.length*self.width
        print('%s的面积为%s'%(self.name,s))
    @classmethod
    def volumn(cls,length,width,height):  #第一个参数为cls,即类
        v=length*width*height
        print('访问类的属性%s'%cls.tag)  #类方法可以访问类的属性
        print('类%s的体积为%s'%(cls,v))
    @staticmethod
    def haha(x,y):  #静态方法既没有类cls参数,也没有实例self参数,因此不能访问类和实例的属性
        print('From staticmethod,%s and %s is haha'%(x,y))
    def hahahaha(x,y): #可以这样定义普通方法,但不建议这样使用,没有意义
        print('From common method,%s and %s is hahahaha' % (x, y))
room1=room('room1',10,13,3)
room1.square #直接调用求面积的函数方法就可以执行函数,而不需要加()
room.volumn(10,13,3)  #类调用类方法时,将类自身作为第一个参数传入
room.haha('Jane','Alan')
room.hahahaha('Jane','Alan')

# 执行结果:
# room1的面积为130
# 访问类的属性1
# 类<class '__main__.room'>的体积为390
# From staticmethod,Jane and Alan is haha
# From common method,Jane and Alan is haha
class A(object):  
    bar = 1  
    def foo(self):  
        print 'foo'  
 
    @staticmethod  
    def static_foo():  
        print 'static_foo'  
        print A.bar  
 
    @classmethod  
    def class_foo(cls):  
        print 'class_foo'  
        print cls.bar  
        cls().foo()  
  
A.static_foo()  
A.class_foo()  
上一篇下一篇

猜你喜欢

热点阅读