python Class:物件導向進階編程

來源:互聯網
上載者:User

標籤:yellow   技術分享   isp   roc   rgb   ati   indent   col   vpd   

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

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__

  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


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



python Class:物件導向進階編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.