Python方法和属性的动态绑定 --面向对象

需要了解的:
__ slots __:属于魔术变量,即:系统实现某些特定功能的变量
__ slots __:
1.限定类实例能添加的属性
2.对当前类起作用,对继承的子类是不起作用的
实操:
# coding:utf8
import traceback

from types import MethodType


class CustomClass(object):
    pass


# class CustomClass(object):
#     __slots__ = ['name', 'set_name']


def set_name(self, name):
    self.name = name


custom_class = CustomClass()
custom_class.name = "Thanlon"  # 动态添加属性
custom_class.set_name = MethodType(set_name, custom_class)  # 添加set_name方法作用在cusClass类中
custom_class.set_name("Tangtang")
print(custom_class.name)
try:
    custom_class.sex = '女'
    print(custom_class.sex)
except AttributeError:
    traceback.print_exc()


class ExtMyClass(CustomClass):
    pass


ext_class = ExtMyClass()
ext_class.sex = '男'
print(ext_class.sex)

posted @ 2019-04-20 13:14  牛新龙的IT技术博客  阅读(263)  评论(0编辑  收藏  举报