您好,登錄后才能下訂單哦!
一、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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。