python类动态增加属性和方法

一、动态添加属性
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)  # 狗粮

参考:https://www.cnblogs.com/semon-code/p/8257826.html

  • 7
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值