一、Class添加新方法: MethodType
站在用户的角度思考问题,与客户深入沟通,找到呼图壁网站设计与呼图壁网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站制作、成都网站建设、外贸营销网站建设、企业官网、英文网站、手机端网站、网站推广、域名与空间、虚拟主机、企业邮箱。业务覆盖呼图壁地区。
外挂类
class Animal(object):
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print 'Animal is run'
def set_color(self, color):
self.color = color;
print color
dog = Animal('Pity', 9)
cat = Animal('Miumiu', 9)
from types import MethodType
dog.set_color = MethodType(set_color, dog, Animal)
dog.set_color('yellow')
print dog.color
cat.set_color('white_yellow')
由此可见,MethodType指定添加在dog对象中,而非Animal中
2.内嵌类
class Animal(object):
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print 'Animal is run'
def set_color(self, color):
self.color = color;
print color
dog = Animal('Pity', 9)
cat = Animal('Miumiu', 9)
from types import MethodType
Animal.set_color = MethodType(set_color, None, Animal)
dog.set_color('yellow')
cat.set_color('white_yellow')
格式图:
二、Class限制添加新元素:__slots__
普通的Class没有限制添加元素
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print 'Animal is run'
dog = Animal('Pity', 9)
dog.color = 'yellow' #dog实体添加了新元素color
print dog.color
2.限制添加新元素:__slots__
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
__slots__ = ('name', 'age') #限制实体添加其他元素
def __init__ (self, name, age):
self.name = name
self.age = age
def run(self):
print 'Animal is run'
dog = Animal('Pity', 9)
print dog.name
dog.color = 'yellow'
!!!但是!!!!!
对于继承Animal的子类来讲,这个方法无效,除非在子类中也添加__slots__
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
__slots__ = ('name', 'age')
def __init__ (self, name, age):
self.name = name
self.age = age
def run(self):
print 'Animal is run'
class Cat(Animal): #添加继承Animal的子类
pass
cat = Cat('Miumiu', 9)
cat.color = 'white_yellow'
print cat.color