理解python中的__str__, __call__, __init__, __getattr__
来源:互联网 发布:淘宝店铺如何更换行业 编辑:程序博客网 时间:2024/05/29 03:57
解释
__getattr__:当调用不存在的属性时访问这个方法
__str__:对象打印出来的字符串(返回用户看到的)
__repr__:对象打印出来的字符串(返回开发者看到的)
__call__:如果类实现了这个方法,相当于把这个类型的对象当作函数来使用,相当于 重载了括号运算符
实例:
class MyClass(object): def __call__(self, num): print("in __call__: %s", num) def __init__(self, num): self.num = num def __str__(self): print("in __str__") return "test" def __repr__(self): print("in __repr__") return "test2"a = MyClass(4)print aprint a(75)a(80)
运行结果
__init__:
__getitem__:对象像list那样按照下标取出元素(注意:如若需要使用切片等方法需要自己实现)
实例
import sys, osclass UrlChain(object): def __init__(self, path=''): print("in __init__") self._path = path def __getattr__(self, guan): print("in __getattr__") print("in __getattr__: %s" % guan) return UrlChain('%s/%s' % (self._path, guan)) def __str__(self): print("in __str__") return self._path def __call__(self, index): print("in __call__") return UrlChain('%s/%s' % (self._path, index))class CephManager(object): base_url = UrlChain('v1') def func1(self): print self.base_url.clusters('JeffreyGuan')cm = CephManager()cm.func1()
运行结果
0 0
- 理解python中的__str__, __call__, __init__, __getattr__
- python类中的__call__、__init__、__getattr__、__setattr__、__setattr__详解
- Python中的__init__,__call__
- Python中的__init__,__call__
- Python __new__, __init__, __metaclass__, __call__, __del__, __getattr__, __getattribute__
- python中__init__、__getattr__、__setattr__、__call__的使用
- python __getattr__()、__call__
- python __getattr__ 与 __call__
- python __str__,__repr__,__call__()
- Python __new__ ,__init__,__call__
- python __init__ __new__ __call__
- python __new__、__init__、__call__
- python中__str__, __call__方法
- python中的__init__ 、__new__、__call__小结及使用
- python中的__init__ 、__new__、__call__小结及使用
- Python中的__new__、__init__、__call__三个特殊方法
- 详解Python中的__new__、__init__、__call__三个特殊方法
- Python __call__ 和 __init__ 区别
- 球虫机器人(ballbot)数学建模及控制方法研究
- bzoj4818【SDOI2017】序列计数 矩阵快速幂+动态规划
- LeetCode077 Combinations
- Myeclipse建立Maven
- matlab 实现图像的二值化、对比度拉伸变化
- 理解python中的__str__, __call__, __init__, __getattr__
- Java封装,继承和多态总结
- Object对象
- 项目中遇到的问题
- LeetCode078 Subsets
- 一个简单的贪吃蛇
- java学习笔记13——JDBC初步
- Python中使用NLTK库解决错误:LookupError: from nltk.book import
- Canvas中的drawImage