初始类为
import types
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
if __name__ == '__main__':
p=Person('kb',18)
1、动态增加一个类属性
Person.sex='女'
2、类不能调用实例对象
print(Person.age)
报错:
AttributeError: type object ‘Person’ has no attribute ‘age’
3、对象调用类属性
print(p.sex)
4、动态增加实例方法
def run(self,work):
print(f'实例方法:{self.name}正在{work}')
p.run=types.MethodType(run,p)
p.run('学习')
5、给Person类增加一个类方法
@classmethod
def class_run(cls,work):
print(f'类方法:正在{work}')
Person.class_run=class_run
p.class_run('学习')
6、给Person类增加一个静态方法
@staticmethod
def static_run(work):
print(f'静态方法:正在{work}')
Person.static_run=static_run
p.static_run('学习')