python-静态方法staticmethod、类方法classmethod、属性方法property

来源:互联网 发布:如何编译java程序 编辑:程序博客网 时间:2024/06/08 12:38

类的普通方法

class Animal(object):    def __init__(self,name):        self.name = name    def intro(self):        print('there is a %s'%(self.name))cat = Animal('cat')cat.intro()

静态类方法

class Animal(object):    def __init__(self,name):        self.name = name    @staticmethod    def intro(self):        print('there is a %s'%(self.name))cat = Animal('cat')cat.intro()

加上装饰器后运行会报错,原因是方法变为一个普通函数,脱离的与类的关系,不能引用构造函数中的变量了。
加上装饰器后运行会报错
使用场景举例:python内置方法os中的方法,可以直接使用的工具包,跟类没关系。


class Animal(object):    def __init__(self,name):        self.name = name    @classmethod    def intro(self):        print('there is a %s'%(self.name))cat = Animal('cat')cat.intro()

报错信息
这里写图片描述
如果换成

class Animal(object):    name = 'cat'    def __init__(self,name):        self.name = name    @classmethod    def intro(self):        print('there is a %s'%(self.name))cat = Animal('cat')cat.intro()

可以正常运行。
结论:类方法只能调用类变量,不能调用实例变量


属性方法@property 把一个方法变为(伪装成)类属性。因为类属性的实质是一个类变量,用户可以调用变量就可以修改变量。某些特定场景要限制用户行为,就用到静态方法。
@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。(摘自廖雪峰的博客)

class Animal(object):    def __init__(self,name):        self.name = name    @property    def intro(self,food):        print('there is a %s eating %s'%(self.name,food))cat = Animal('cat')cat.intro()

报错:这里写图片描述
方法不能正常调用。如果要调用,如下:

cat.intro

但是这样的话,方法就没办法单独传入参数。如果要传入参数,如下:

class Animal(object):    def __init__(self,name):        self.name = name    @property    def intro(self):        print('there is a %s eating %s'%(self.name,food))    @intro.setter    def intro(self,food):        passcat = Animal('cat')cat.intro

cat.intro还有其他操作getter deleter等等。

阅读全文
0 0
原创粉丝点击