python 面向?qū)ο?/h2>

想把屬性設為private 在前面加__

獲取對象信息

type()

我們來判斷對象類型,使用type()函數(shù)

type(123)
#<class 'int'>

但是type()函數(shù)返回的是什么類型呢?它返回對應的Class類型。如果我們要在if語句中判斷,就需要比較兩個變量的type類型是否相同

import types
type(lambda x: x)==types.LambdaType

isinstance

a = Animal()
d = Dog()
isinstance(d, Husky) #True

dir()

dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

類似xxx的屬性和方法在Python中都是有特殊用途的,比如len方法返回長度。在Python中,如果你調(diào)用len()函數(shù)試圖獲取一個對象的長度,實際上,在len()函數(shù)內(nèi)部,它自動去調(diào)用該對象的len()方法

slot

正常情況下,當我們定義了一個class,創(chuàng)建了一個class的實例后,我們可以給該實例綁定任何屬性和方法,這就是動態(tài)語言的靈活性。

def set_age(self, age): # 定義一個函數(shù)作為實例方法
    self.age = age
from types import MethodType
s.set_age = MethodType(set_age, s)
s.set_age(25)

同理,可以給Class綁定方法

Student.set_score = set_score

如果我們想要限制實例的屬性怎么辦?比如,只允許對Student實例添加name和age屬性

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定義允許綁定的屬性名稱

s = Student() # 創(chuàng)建新的實例
s.name = 'Michael' # 綁定屬性'name'
s.age = 25 # 綁定屬性'age'
s.score = 99 # 綁定屬性'score' #error

使用slots要注意,slots定義的屬性僅對當前類實例起作用,對繼承的子類是不起作用的

@property

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
s = Student()
>>> s.score = 60 # OK,實際轉(zhuǎn)化為s.set_score(60)
>>> s.score # OK,實際轉(zhuǎn)化為s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  

多重繼承

class Runnable(object):
    def run(self):
        print('Running...')
class Mammal(Animal):
    pass
class Dog(Mammal, Runnable):
    pass

枚舉類

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

如果需要更精確地控制枚舉類型,可以從Enum派生出自定義類:

from enum import Enum,unique

@unique
class Weekday(Enum):
    Sun = 0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

@unique裝飾器可以幫助我們檢查保證沒有重復值。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容