staticmethod classmethod property方法

@staticmethod 静态方法

函数修饰符,用来修饰一个函数,类似于装饰器

class Dog(object):
    def __init__(self,name):
        self.name = name

    def eat(self,food):
        print(‘%s is eating %s‘%(self.name,food))

d = Dog(‘二哈‘)
d.eat(‘包子‘)      #二哈 is eating 包子

eat()方法上面加上 @staticmethod

class Dog(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def eat(self,food):
        print(‘%s is eating %s‘%(self.name,food))

d = Dog(‘二哈‘)
d.eat(‘包子‘)  #TypeError: eat() missing 1 required positional argument: ‘food‘

提示 food 少传递一个参数

删除food参数尝试下

class Dog(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def eat(self):
        print(‘%s is eating %s‘%(self.name,‘包子‘))

d = Dog(‘二哈‘)
d.eat()  #TypeError: eat() missing 1 required positional argument: ‘self‘

提示少一个位置参数self ,self默认不是自动传进去的吗,静态方法就是截断方法与类的联系,就是说eat在这里就只是一个单纯的函数。

调用方式:类名。静态方法() 也可以用对象调用方法的方式。

class Dog(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def eat():
        print(‘%s is eating %s‘%(‘5545‘,‘包子‘))

d = Dog(‘二哈‘)
d.eat()    #5545 is eating 包子
Dog.eat() #5545 is eating 包子

要在静态方法里面调用self,就必须把self本身传进去

class Dog(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def eat(self):
        print(‘%s is eating %s‘%(self.name,‘包子‘))

d = Dog(‘二哈‘)
d.eat(d)       #二哈 is eating 包子

静态方法名义上归类管理,实际上调用不了类或者实例的任何属性。

@classmethod  类方法

函数修饰符,同样用来装饰函数

class Dog(object):
    def __init__(self,name):
        self.name = name
    @classmethod
    def eat(self):
        print(‘%s is eating %s‘%(self.name,‘包子‘))

d = Dog(‘二哈‘)
d.eat() #AttributeError: type object ‘Dog‘ has no attribute ‘name‘

尝试访问类变量

class Dog(object):
    name= ‘秋田‘
    def __init__(self,name):
        self.name = name
    @classmethod
    def eat(self):
        print(‘%s is eating %s‘%(self.name,‘包子‘))

d = Dog(‘二哈‘)
d.eat() #秋田 is eating 包子

类方法只能访问类变量,不能访问实例变量。

property 属性方法

class Dog(object):
    name= ‘秋田‘
    def __init__(self,name):
        self.name = name
    @property
    def eat(self):
        print(‘%s is eating %s‘%(self.name,‘包子‘))

d = Dog(‘二哈‘)
d.eat() #TypeError: ‘NoneType‘ object is not callable

去掉括号

class Dog(object):
    name= ‘秋田‘
    def __init__(self,name):
        self.name = name
    @property
    def eat(self):
        print(‘%s is eating %s‘%(self.name,‘包子‘))

d = Dog(‘二哈‘)
d.eat  #二哈 is eating 包子

把一个方法变成静态属性

作为一个属性,如果有参数要怎么传递?

既然是属性就是可以赋值的。

class Dog(object):
    name= ‘秋田‘
    def __init__(self,name):
        self.name = name
    @property
    def eat(self,food):
        print(‘%s is eating %s‘%(self.name,food))

d = Dog(‘二哈‘)
d.eat = ‘包子‘ #AttributeError: can‘t set attribute

直接赋值也是不可以的,同样需要装饰下

class Dog(object):
    name= ‘秋田‘
    def __init__(self,name):
        self.name = name
        self._food = None
    @property
    def eat(self):
        print(‘%s is eating %s‘%(self.name,self._food))
    @eat.setter
    def eat(self,food):
        print(‘set food is‘,food)
        self._food = food

d = Dog(‘二哈‘)
d.eat = ‘包子‘ #set food is 包子
d.eat           #二哈 is eating 包子

属性赋值会触发 @eat.setter 下的 eat()方法。

删除属性

class Dog(object):
    name= ‘秋田‘
    def __init__(self,name):
        self.name = name
        self.__food = None
    @property
    def eat(self):
        print(‘%s is eating %s‘%(self.name,self._food))
    @eat.setter
    def eat(self,food):
        print(‘set food is‘,food)
        self.__food = food

d = Dog(‘二哈‘)
d.eat = ‘包子‘
d.eat
del d.eat #AttributeError: ‘Dog‘ object has no attribute ‘_food‘

默认是不能删除的,如果非要删除就要重写

class Dog(object):
    name= ‘秋田‘
    def __init__(self,name):
        self.name = name
        self.__food = None
    @property
    def eat(self):
        print(‘%s is eating %s‘%(self.name,self.__food))
    @eat.setter
    def eat(self,food):
        print(‘set food is‘,food)
        self.__food = food

    @eat.deleter
    def eat(self):
        del self.__food
        print(‘删除成功‘)

d = Dog(‘二哈‘)
d.eat = ‘包子‘ set food is 包子
d.eat  # 二哈 is eating 包子
del d.eat  # 删除成功
d.eat   # AttributeError: ‘Dog‘ object has no attribute ‘_Dog__food‘

d.eat调用了@property下的eat  因为这个方法里面有调用self.__food 而这个属性被删除了

有些场景不能简单的通过定义静态属性来实现的。所有要把方法做成属性。比如有些接口的API。

时间: 2024-10-25 02:48:24

staticmethod classmethod property方法的相关文章

Python学习之路:staticmethod classmethod property方法

参考链接:http://www.cnblogs.com/alex3714/articles/5213184.html 静态方法 只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性 class Dog(object): def __init__(self,name): self.name = name @staticmethod #实际上跟类没什么关系了 def eat(self): print("%s is eating %s"%(self.name,'dd')) de

Python @staticmethod, @classmethod, @property

@staticmethod, @classmethod, @property 用法及作用 class Foo(object) : def __init__(self) : self._name = "property test" print "init" def test(self) : print "class method" @property def name(self) : return self._name @staticmethod

类的特殊方法 staticmethod classmethod property

staticmethod方法 1 #staticmethod 被装饰的方法与类本身没有任何关系,不能使用类的任何属性,不用实例化直接通过类名进行调用,默认不会将实例self作为实参传递 2 class Foo7(object): 3 def __init__(self, name): 4 self.name = name 5 @staticmethod 6 def get_staticmethod(name): 7 print("my staticmethod name is %s"%

staticmethod&classmethod&property

property 是将一个方法变成属性class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError(

python 类中staticmethod,classmethod,普通方法

1.staticmethod:静态方法和全局函数类似,但是通过类和对象调用. 2.classmethod:类方法和类相关的方法,第一个参数是class对象(不是实例对象).在python中class也是一个真实存在于内存中的对象,不同于其他语言只存在于编译期间. 3.普通方法和实例相关的方法,通过类实例调用. 4.代码示例 #coding:utf-8 ''' Created on 2015年5月29日 @author: canx ''' class Person: def __init__(se

staticmethod classmethod修饰符

一.staticmethod(function) Return a static method for function.A static method does not receive an implicit first argument. To declare a static method, use this idiom: class Sing(): @staticmethod def sayHello(): print "hello world" def sayNo(): pr

python staticmethod,classmethod方法的使用和区别以及property装饰器的作用

class Kls(object): def __init__(self, data): self.data = data def printd(self): print(self.data) @staticmethod def smethod(*arg): print('Static:', arg) @classmethod def cmethod(*arg): print('Class:', arg) >>> ik = Kls(23) >>> ik.printd()

@classmethod, @staticmethod和@property这三个装饰器的使用对象是在类中定义的函数。下面的例子展示了它们的用法和行为:

class MyClass(object): def __init__(self): self._some_property = "properties are nice" self._some_other_property = "VERY nice" def normal_method(*args,**kwargs): print "calling normal_method({0},{1})".format(args,kwargs) @cla

python之内置装饰器(property/staticmethod/classmethod)

python内置了property.staticmethod.classmethod三个装饰器,有时候我们也会用到,这里简单说明下 1.property 作用:顾名思义把函数装饰成属性 一般我们调用类方法成员,都是如下写法: class propertyTest(): def __init__(self,x,y): self.x = x self.y = y def square(self): return self.x * self.y pt = propertyTest(3,5) print