重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

pythonClass:面向对象高级编程-创新互联

一、Class添加新方法: MethodType

创新互联公司是一家专注于网站设计、成都做网站与策划设计,关岭网站建设哪家好?创新互联公司做网站,专注于网站建设10年,网设计领域的专业建站公司;建站业务涵盖:关岭等地区。关岭做网站价格咨询:028-86922220
  1. 外挂类

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')

python Class:面向对象高级编程

print dog.color

python Class:面向对象高级编程

cat.set_color('white_yellow')

python Class:面向对象高级编程

由此可见,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')

python Class:面向对象高级编程

cat.set_color('white_yellow')
python Class:面向对象高级编程

格式图:

python Class:面向对象高级编程

二、Class限制添加新元素:__slots__

  1. 普通的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

python Class:面向对象高级编程

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

python Class:面向对象高级编程

dog.color = 'yellow'

python Class:面向对象高级编程

!!!但是!!!!!

对于继承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

python Class:面向对象高级编程

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


当前名称:pythonClass:面向对象高级编程-创新互联
本文来源:http://cqcxhl.com/article/jgidd.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP