Python基礎——7面向對象高級編程

實例與類動態添加方法

實例添加屬性:python

def Student(object):函數

    pass對象

s = Student()blog

s.name = ‘syz’繼承

實例添加方法get

from types import MethodTypeit

def set_name(self,name):ast

    self.name = nameclass

s.set_name = MethodType(set_name,s)效率

類添加方法

Student.set_name = set_name

__slots__

限定動態添加類的屬性,經過tuple的方式

__slots__=(‘name’,’score’)

限定動態添加的屬性只能是name 跟score

相似的__x__的方法屬於特殊方法,例如__init__方法、自帶str類的__len__()方法,讓該方法做用於class,len(‘123’),而普通的len()方法則須要經過x.len()使用

@property

因爲檢查參數須要添加get或者set函數,而爲了提升訪問的效率,能夠經過修飾器的方式修改get或者set函數的方式,類能夠經過student.a或者student.a=a的方式直接調用類的函數。

calss Student(object):
    @property
    def birth(self):
        return self._birth
    @birth.setter(self,value):
        if birth > 100:
            self._birth = value
        else:
            raise ValueError(‘birth must be in 200!’)  #讀寫

    @property
    def age(self):
        return self._age       #只讀

多重繼承

多重繼承的父類後面加上MaxIn用以區分

calss dag(Animal,CanrunMaxIn,EatFeatMaxIn):

    pass

__str__  __call__  callable()   __getattr__

__str__直接打印函數是能夠查看重要的參數

calss Student(object):
def __str__(self):
    print(‘重要參數!’)
    __repr__ = __str__
print(Student())
s = Student()
print(s)

__call__考慮把類當成函數調用時

Student()

class Student(object):
    def __init__(self, name):
        self.name = name

    def __call__(self):
        print('My name is %s.' % self.name)

調用方式以下:

>>> s = Student('Michael')
>>> s() # self參數不要傳入
My name is Michael.

那麼,怎麼判斷一個變量是對象仍是函數呢?其實,更多的時候,咱們須要判斷一個對象是否能被調用,能被調用的對象就是一個Callable對象,好比函數和咱們上面定義的帶有__call__()的類實例:

>>> callable(Student())
True
>>> callable(max)
True
>>> callable([1, 2, 3])
False
>>> callable(None)
False
>>> callable('str')
False

__getattr__ 當調用的屬性爲動態的時,進行設置

class Student(object):

    def __getattr__(self, attr):
        if attr=='age':
            return lambda: 25
        raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)

這實際上能夠把一個類的全部屬性和方法調用所有動態化處理了,不須要任何特殊手段。

這種徹底動態調用的特性有什麼實際做用呢?做用就是,能夠針對徹底動態的狀況做調用

枚舉類

把固定不變的數以枚舉類的實例形式實現

例如日期、月份等

from enum import Enum

Mouth = Enum(‘Month’,(‘Jan’’Feb’))

from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
from enum import Enum, unique

@unique
class Weekday(Enum):
    Sun = 0 # Sun的value被設定爲0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

value屬性則是自動賦給成員的int常量,默認從1開始計數。

若是須要更精確地控制枚舉類型,能夠從Enum派生出自定義類:

from enum import Enum, unique

@unique
class Weekday(Enum):
    Sun = 0 # Sun的value被設定爲0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

@unique裝飾器能夠幫助咱們檢查保證沒有重複值。

訪問這些枚舉類型能夠有若干種方法:

>>> day1 = Weekday.Mon
>>> print(day1)
Weekday.Mon
>>> print(Weekday.Tue)
Weekday.Tue
>>> print(Weekday['Tue'])
Weekday.Tue
>>> print(Weekday.Tue.value)
2
>>> print(day1 == Weekday.Mon)
True
>>> print(day1 == Weekday.Tue)
False
>>> print(Weekday(1))
Weekday.Mon
>>> print(day1 == Weekday(1))
True
>>> Weekday(7)
Traceback (most recent call last):
  ...
ValueError: 7 is not a valid Weekday
>>> for name, member in Weekday.__members__.items():
...     print(name, '=>', member)
...
Sun => Weekday.Sun
Mon => Weekday.Mon
Tue => Weekday.Tue
Wed => Weekday.Wed
Thu => Weekday.Thu
Fri => Weekday.Fri
Sat => Weekday.Sat
相關文章
相關標籤/搜索