Python(6) class里的下划线变量和函数们 __init__
来源:互联网 发布:数据一致性数据治理 编辑:程序博客网 时间:2024/06/06 00:18
warning: 环境为python3.6
这篇主要研究一下python的class里面那些开头为下划线的变量和函数
变量
- _xxx 不能用’from module import *’导入
- “单下划线” 开始的成员变量叫做保护变量,意思是只有类对象和子类对象自己能访问到这些变量;
- “双下划线” 开始的成员变量叫做私有变量,意思是只有类对象自己能访问,连子类对象也不能访问到这个数据。
前两句话其实是不对的,如果是单下划线开始的成员变量(函数也是一样),那么仍然可以从外部访问,并且也同样可以以from module import 的方式引入到别的文件里,可以自己试试。
class a: _g = 10 def _t(self): # self表示当前的实例 print("_t") if __name__ == '__main__': test = a() print(test._g) # 会打印一个10出来 test._t() # 会打印'_t'出来
而第三句是对的,包括以双下划线为开头的自定义函数,都是不能从外部访问的
class a: __g = 10 def __t(self): print("__t") class b(a): def h(self): print(super().__getattribute__('__g')) super().__t() if __name__ == '__main__': test = a() print(test.__g) # 会报AttributeError: 'a' object has no attribute '__g' test.__t() # 会报AttributeError: 'a' object has no attribute '__t' test = b() test.h() # AttributeError: 'b' object has no attribute '__g'/'__t'
但是呢,如果这样写
class a: def __t__(self): print('__t__')class b(a): def h(self): super().__t__()if __name__ == '__main__': test = b() test.h() # 会打印'__t__'出来
以双下划线开头和结尾的函数名和变量(foo)代表python里特殊方法专用的标识
函数
__new__(cls)
这是当一个对象正在被实例化的时候执行的,它的执行顺序位于__init__之前。cls表示需要被实例化的类,这个函数必须要return一个实例回来。
__init__()
这是python类的构造函数,是当一个对象实例化完成后执行的,对变量进行初始化操作。
class a: def __init__(): print('init') def __new__(cls): print('new') return super().__new__(cls)if __name__ == '__main__': test = a()# 输出结果会是newinit
__name__()
def a(): print("haha")if __name__ == '__main__': print(a.__name__) # print(a.__class__) 返回的是<class function> f = a f()# 输出结果会是ahaha
__call__()
在python中,函数其实是可调用的对象。可以通过实现__call__(),将类实例变成可调用的对象,
class A: def __call__(self, *args, **kwargs): print("haha") for i in args: print(i)a = A()a(1, 2, 3, 4)# 输出结果会是haha1234
__str__()
在python中,实现str()必须返回一个string,然后直接输出类的实例,这样可以输出这个string。这个功能可以用来打印一个类里面的各种属性。
class A: def __str__(self): return "str"a = A()print(a)# 输出结果会是str
后面再继续补充23333
super()是用来调用父类的函数和变量,详细可参考这篇博客
阅读全文
0 0
- Python(6) class里的下划线变量和函数们 __init__
- python 里的import 和__init__
- 使用Python类的 __init__( ) 函数定义成员变量
- Python类里的__init__方法函数,Python类的构造函数
- Python class的__new__与__init__方法
- python中那些双下划线开头得函数和变量
- python中那些双下划线开头得函数和变量
- python中那些双下划线开头得函数和变量
- Python下划线和私有变量
- Python类中__init__函数和self参数的关系
- python下划线变量的含义
- python下划线变量的含义
- python下划线变量的含义
- python下划线变量的含义
- python下划线变量的含义
- python下划线变量的含义
- Python中的__init__()和__call()__函数
- 初学python class 注意构造函数__init__(self)
- 《四》引入静态文件并输出视图文件
- A+B Problem (Case Count)
- 对于JavaScript中原型链的理解
- LeetCode 35. Search Insert Position
- 利用 Python 进行数据分析(十二)pandas:数据合并
- Python(6) class里的下划线变量和函数们 __init__
- 四、JNDI
- 【mycat】mycat在windows环境下的安装和启动
- Struts 2国际化
- OpenGL学习笔记(十)
- A+B Problem (0)
- View绘制
- TCP为什么需要三次握手,又为什么需要4次挥手?
- HDFS的API调用,创建Maven工程,创建一个非Maven工程,HDFS客户端操作数据代码示例,文件方式操作和流式操作