一.__slots__属性
__slots__属性是在定义一个类时可添加的用于限制类的实例对象中属性和方法的一个东西;
class Animal():
__slots__ = ('run','eat','food','name') #只能在实例对象中添加以上四个属性或方法
def __init__(self,name):
self.name = name
a = Animal('The dog')
a.food = 'meat'
from types import MethodType as mt
a.run = mt(lambda self:print(self.name + " is running."),a)
a.eat = mt(lambda self:print(self.name + "'s favorite food is " + a.food + '.'),a)
a.run()
a.eat()
##
The dog is running.
The dog's favorite food is meat.
注意点有二:
1.__slots__属性并不限制动态的给类添加属性和方法;
2.__slots__的限制只对当前一代有用,对继承后的子类不起作用,如果对子类也添加了__slots__属性,那么限制范围将是父类与子类的的和;
二.type()函数
type()函数只有一个参数时返回对象的类型,当有三个参数时返回新的类型对象,因此可以利用type()函数来动态创建类;
type()语法格式:
type(object)
type(name,bases,dict)
- name :对象的名称;
- bases:基类元组;
- dict :字典,类中定义的命名空间变量;
使用实例:
def frun(self):
print("He is running.")
Dog = type('Dog',(object,),dict(run=frun,age=6)) #注意这里object后的逗号,因为Python支持多继承
d = Dog()
print(type(Dog))
print(d.age)
d.run()
##
<class 'type'>
6
He is running.
注意这里Dog的类型是type,事实上利用class定义的类也是type,用class定义类的本质即是Python解释器用type()函数来实现的;