python self最基本主要的原理

主要用法

在python中self用来表示某个类的实例自己。 使用此关键字可以在python中访问类的属性和方法。 它将属性与给定参数绑定在一起。 我们使用self的原因是Python不使用“ @”语法来引用实例属性。

举例

class car():
	def __init__(self, model, color):	#init method or constructor(类似构造函数)
		self.model = model
		self.color = color
	
	def show(self):
		print("Model is", self.model)
		print("Color is", self.color)

输入

audi = car("audi a6", "black")			##both objects have different self whiich
ferrari = car("ferrari 488", "green")	#contain their attributes

audi.show()		#same as car.show(audi)
ferrari.show()	#same as car.show(ferrari)

输出

Model is audi a6
color is black
Model is ferrari 488
color is green

猜你喜欢

转载自blog.csdn.net/qq_41731507/article/details/113745772