您好,欢迎来到叨叨游戏网。
搜索
您的当前位置:首页Python类知识

Python类知识

来源:叨叨游戏网


类也是一个对象

构造方法和析构方法

def __init__(self [, 形参列表]):		#构造方法
	语句...

__del__(self):						#析构方法
#不建议在析构方法中进行操作,因为析构调用的时间
#即对象销毁的时间不确定

实例方法

def name(self,...)		#传self,对实例属性和方法进行操作

类的方法

class Dog:
	local = "China"
	def __init__(self,a):
		self.age = a
	@classmethod			#表明是类方法
	def show(cls):			#class->简写cls
		print(cls.local)	#使用类变量cls.local
d=Dog(1)
Dog.show()				#类调用类方法
d.show()				#实例调用类方法

类变量和实例变量

class Dog:
	age = 1			#类变量
	def __init__(self, name):
			self.name_=name		#实例变量

通过实例访问变量时,现在实例变量中查找,再去类变量查找
实例对类变量进行操作时,操作的实际上是对类变量深拷贝的变量
实例变量与类变量若名称相同时,实例变量将屏蔽掉类变量(实际操作发现:该屏蔽仅是在实例访问变量时屏蔽,通过类名依旧可以访问类变量,说明类变量与实例变量相同名称时依旧存在)

静态方法

特点是不需要传self、cls

class Dog:
	local = "China"
	def __init__(self,a):
		self.age = a
	@staticmethod			#表明静态方法
	def add(a,b):			#不需要传self or cls
		return a+b	
	@classmethod
	def show(cls):
		print(cls.add(1,1),cls.local)
							#类方法调用静态方法
d=Dog(1)
print(d.add(1,1))			#实例调用静态方法
Dog.show()

内置属性

__class__、__dict__、__doc__、__module__

print(d.__dict__)			#d为类的一个实例
#以字典形式把实例的所有属性打印出来

类变量

类的变量用类和实例都能调用但是实际上是实例对类变量深拷贝

class Dog:
	local = "China"
	def __init__(self,a):
		self.age = a
d=Dog(1)
print("d.local= ",d.local,"	","Dog.local= ",Dog.local)
#China		China
d.local="earth"
print("d.local= ",d.local,"	","Dog.local= ",Dog.local)
#earth		China

对象的属性管理

getattr(obj,name [,default])		#获取属性
setattr(obj,name,value)			#添加一个属性
hasattr(obj,name)				#判断有没有这个属性
delattr(obj,name)				#删除

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- gamedaodao.net 版权所有 湘ICP备2024080961号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务