Article / 文章中心

Python编程:类的实例动态增加属性和方法

发布时间:2021-11-23 点击数:109
# -*- coding: utf-8 -*-  # @File    : 类的实例动态增加属性和方法.py # @Date    : 2018-05-31 # @Author  : Peng Shiyu  class Person(object):  count = 0  def __init__(self, name):  self.name = name   if __name__ == '__main__':  # 实例化  p1 = Person("tom")  print(p1.name)  # tom  print(p1.count)  # 0   p2 = Person("jack")  print(p2.name)  # jack  print(p2.count)  # 0   # 通过实例修改类变量  p1.count = 2  print(p1.count)  # 2  print(p1.count)  # 2  print(Person.count)  # 0   # 通过类修改类变量  Person.count = 3  print(p1.count)  # 2  print(p1.count)  # 2  print(Person.count)  # 3   # 给实例增加属性  p1.age = 23  print(p1.age)  # 23   # 给实例增加方法  def set_age(self, age):  self.age = age   from types import MethodType  p1.set_age = MethodType(set_age, p1)  p1.set_age(25)   print(p1.age)  # 25   print(p2.age)  # AttributeError: 'Person' object has no attribute 'age'