码迷,mamicode.com
首页 > 编程语言 > 详细

Python __init__ 特殊方法

时间:2018-04-08 00:12:03      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:append   方法   打印   第一个   ast   define   需要   font   操作   

在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]
>>> 

  

  

Python __init__ 特殊方法

标签:append   方法   打印   第一个   ast   define   需要   font   操作   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!