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
- python-静态方法staticmethod、类方法classmethod、属性方法property
- Python描述符,属性,方法,修饰符property,staticmethod,classmethod
- python 静态方法staticmethod和类方法classmethod
- 静态方法和类方法, staticmethod & classmethod
- @classmethod类放和@staticmethod静态方法
- python的静态方法以及@staticmethod或@classmethod的区别
- Python 实例方法、@staticmethod和@classmethod
- Python 实例方法、@staticmethod和@classmethod
- Python 实例方法、@staticmethod和@classmethod
- python的classmethod和staticmethod方法
- Python 实例方法、@staticmethod和@classmethod
- python之静态和类方法:staticmethod和classmethod内置函数
- Python 静态方法 @staticmethod
- python 类中@staticmethod,@classmethod和实例方法
- 我所理解的实例方法、类方法(@classmethod)和静态方法(@staticmethod)(关键词:实例方法/类方法/@classmethod/静态方法/@staticmethod)
- python @ property classmethod staticmethod
- Python中staticmethod方法和classmethod方法区别
- python 中 @classmethod 、staticmethod 和 普通方法 的区别
- Facebook面部识别新突破:可识别未标记照片中用户
- 硅谷顶级VC:“S曲线”看四大风口,创企成功机会巨大
- Android核心程序之SystemUI
- Docker 入门笔记 1
- 如何测量智能产品的AI智商水平,论AI的三种智商 |未来研究
- python-静态方法staticmethod、类方法classmethod、属性方法property
- 解决爬虫中文乱码问题
- 5.数据结构单链表之链表反转
- Jeff Dean| 面向系统的机器学习和面向机器学习的系统
- 非计算机专业,如何学习计算机视觉
- 利用机器学习在15分钟内破解验证码!
- z-index使用注意事项
- 前情回顾,更新至第九篇——AI主题科幻小说《地与光》
- org.apache.ibatis.binding.BindingException【原因汇总】