一、动态添加属性
1、为类添加属性,直接加在类上,会使此后所有实例化对象都具备此属性
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
cat = Animal('小花', 1)
print(cat.name) # 小花
print(cat.category) # AttributeError: 'Animal' object has no attribute 'category'
Animal.category = '短毛' # 直接添加在类上,此后实例化的所有对象都会有category属性
new_cat = Animal('小咪', 1)
print(new_cat.age) # 1
print(new_cat.category) # 短毛
next_cat = Animal('小新', 2)
print(next_cat.name) # 小新
print(new_cat.category) # 短毛
2、为实例对象添加属性,仅此实例对象具备此属性,其他实例对象调用此属性会报 `no attribute`错
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
cat = Animal('小花', 2)
cat.category = '虎斑猫' # 只为此实例对象添加category属性
print(cat.name) # 小花
print(cat.category) # 虎斑猫
new_cat = Animal('小咪', 1)
print(new_cat.age) # 1
print(new_cat.category) # AttributeError: 'Animal' object has no attribute 'category'
dog = Animal('二哈', 3)
dog.category = '哈士奇'
print(dog.name) # 二哈
print(dog.category) # 哈士奇
二 、动态添加方法
1、实例对象动态增加方法,只在本实例存在此方法,其他实例调用会报错
from types import MethodType
class Animal(object):
count = 'asd'
def __init__(self, name, age):
self.name = name
self.age = age
def change_name(self, name):
self.name = name
return self.name
def change_age(self, age):
self.age = age
cat = Animal('小花', 2)
print(cat.age) # 2
cat.change_age = MethodType(change_age, cat)
cat.change_age(10)
print(cat.age) # 10
dog = Animal('二哈', 3)
print(dog.age) # 3
# dog.change_age(5) # AttributeError: 'Animal' object has no attribute 'change_age'
print(dog.age) # 3
三、__slots__的使用
__slots__用于限制类属性,实例对象动态增加属性仅限于__slots__的值内有的字段,直接给类增加属性不受此限制
class Animal(object):
__slots__ = ['name', 'age', "category"]
def __init__(self, name, age):
self.name = name
self.age = age
cat = Animal('小咪', 1)
cat.category = '短毛'
cat.food = '猫粮'
print(cat.name, cat.age, cat.category) # 小咪 1 短毛
print(cat.food) # AttributeError: 'Animal' object has no attribute 'food'
Animal.category = '哈士奇'
Animal.food = '狗粮'
dog = Animal('二哈', 3)
print(dog.name, dog.age, dog.category) # 二哈 3 哈士奇
print(dog.food) # 狗粮
参考:/semon-code/p/