iohannes
Published on 2025-03-17 / 0 Visits

动态添加属性和方法

  1. person.py
class Person():
	def __init__(self,name):
		self.name = name 
  1. main.py
from person import Person
li = Person('李')

# 动态添加属性
li.age = 20
print(li.age)
Person.age = None
print(li.age)

# 动态添加方法
import types
def eat(self):
	print('%s正在吃东西。。'%self.name) 
li.eat = types.MethodType(eat,li) 
li.eat()
 
@staticmethod
def test():
	print('这是一个静态方法。')
Person.test = test
Person.test()
 
@classmethod  #类方法
def test(cls): 
	print('这是一个类方法。')
Person.test = test
Person.test()
  1. 输出
20
20
李正在吃东西。。
这是一个静态方法。
这是一个类方法。