First, class adds a new method:Methodtype
Plug-in class
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 ')
Thus, methodtype specifies to be added in the dog object, not in the animal
2. Inline class
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 ')
Format diagram:
Second,class restrictions Add new elements: __slots__
Normal class does not restrict the addition of elements
#!/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. Restrict adding new elements:__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 '
!!! But!!!!!
For subclasses inheriting Animal , this method is not valid unless __slots__ is added to the subclass.
#!/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
Python Class: Object-oriented advanced programming