python学习笔记之基础操作(九)类 -1- 声明和初始化

版权声明:所有资料资源均应用作教育用途,请勿用作商业用途 https://blog.csdn.net/qq_38876114/article/details/86610009

声明

此处不再记录面向对象编程的相关基本思维,只涉及python具体语法

在python中,类的声明格式如下:

class Dog:
	color = 0
	age = 1
	home = "peking"
	def __init__(self,color,age,home):
		self.color = color
		self.age = age
		self.home = home
		self.weight = 10
	def eat(self,w):
		print("eating!")
		self.weight += w
print(Dog.__dict__)
#{'__module__': '__main__', 'color': 0, 'age': 1, 'home': 'peking', 
#'__init__': <function Dog.__init__ at 0x000001BBAA2C47B8>, 
#'eat': <function Dog.eat at 0x000001BBAA2C4840>, '__dict__': <attribute'__dict__' of 'Dog' objects>, 
#'__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}
dog = Dog(0,1,"shanghai")
dog.test = 0
print(dog.__dict__)
#{'color': 0, 'age': 1, 'home': 'shanghai', 'weight': 10, 'test': 0}

其中,__init__()函数是初始化函数,类似于C语言中的构造函数,self变量可以在构造时不传入,由于python不存在声明变量的过程,因此所有类的属性都不需要提前声明,可以直接在函数或者类中进行复制使用,在变量被使用后会自动插入到类的字典中,类的所有变量和方法都以字典的形式存在__dict__变量中,同时可以在类实例化之后向类中赋值之前没有使用过得值,这和C,java语言需要先声明变量并且未声明的属性无法使用是有很大的区别的

猜你喜欢

转载自blog.csdn.net/qq_38876114/article/details/86610009