对于python类self的理解

*阅读本文章需要一定基础
首先,self直译过来是 自己 的意思。

self指的是当前的实例化本身,例如:

class aaa(object):
	pass
abc = aaa()

这段代码中,self指的是类abc注意不是aaa

再比如:

class HELLO(object):
	pass
hello = HELLO()

这里的self指类hello

在class里定义方法时,第一个参数告诉了python你这个方法是在哪儿的。self指实例化本身,故第一个参数通常为self。第一个参数调用时不需要填。

class test(object):
	def helloworld(self):
		print("hello world")

说的再简单一点儿,self是一个变量,它的值是实例化对象本身。就像__name__一样。
当第一个参数不为self时,调用者需手动输入一个实例化对象。如:

class test(object):
	def helloworld(instantiation_name):
		print("hello world")
a = test()
a.helloworld(a)#将实例化对象作为helloworld()的第一个参数传入helloworld()方法中

猜你喜欢

转载自blog.csdn.net/bianchengxueseng/article/details/118273806
今日推荐