温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python Class:面向对象高级编程

发布时间:2020-06-24 00:11:54 来源:网络 阅读:862 作者:虎皮喵的喵 栏目:编程语言

一、Class添加新方法: MethodType

  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:面向对象高级编程



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI