需要了解的:
__ slots __:属于魔术变量,即:系统实现某些特定功能的变量
__ slots __:
1.限定类实例能添加的属性
2.对当前类起作用,对继承的子类是不起作用的
实操:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# 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)