Python __init__ 特殊方法

在Python中有很多以双下划线开头且以双下划线结尾的固定方法。他们会在特定的时机被触发执行。

__init__ 就是其中之一,它会在实例化之后自动被调用。以完成实例的初始化。

>>> class test:   #定义一个类
	def func(self):
		print('手动调用函数:',id(self))   #打印参数的id

		
>>> a = test()    #实例化对象a
>>> a.func()      #用实例a调用函数func(),会把实例a当成一个参数,并且第一个传入到函数func()中。
手动调用函数: 1794999510856
>>> 
>>> class test:     #定义一个类,里面封装的函数使用了__init__特殊方法,这个方法会在初始化实例时自动调用
	def __init__(self):
		print('初始化实例时自动调用:',id(self))

		
>>> a = test()   #实例化对象a,此时它会自动调用__init__,不需要类似a.func()的操作。
初始化实例时自动调用: 1794999587840
>>> 

“析构”问题引入

>>> a = [1,2,3]
>>> b =a           #变量的指向
>>> b
[1, 2, 3]
>>> a.append(5)
>>> a
[1, 2, 3, 5]
>>> b
[1, 2, 3, 5]
>>> del a      #删除一个变量的指向。
>>> a
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    a
NameError: name 'a' is not defined
>>> b
[1, 2, 3, 5]
>>> 

  

  

原文地址:https://www.cnblogs.com/longxd/p/8735446.html