python基础之动态添加属性和方法

一、添加对象属性:

>>> class student(object):
	pass

>>> stu=student()
>>> stu.name="zhang jie"  #添加对象属性
>>> stu.name
'zhang jie'

二、添加类属性:

>>> class student(object):
	def __init__(self):
		self.name="zhang jie"	
>>> student.persons=218        #添加类属性
>>> a=student()
>>> a.persons
218
>>> b.persons
218

 三、添加对象方法:

>>> from types import MethodType
>>> class student(object):
	def __init__(self):
		self.name="zhang jie"	
>>> def show(self):
		print(self.name)
>>> a=student()
>>> a.show=MethodType(show,a) #添加对象方法
>>> a.show()
zhang jie

四、添加类方法:

>>> class student():
	    pass
>>> def show(self):
	print("class method")

>>> student.show=types.MethodType(show,student) #添加类方法
>>> a=student()
>>> a.show()
class method
>>> b=student()
>>> b.show()
class method

猜你喜欢

转载自blog.csdn.net/Panda996/article/details/84854970
今日推荐