Python 學(xué)習(xí)筆記6 - 面向?qū)ο缶幊?Object Oriented Programming

在Python中,所有數(shù)據(jù)類型都可以視為對(duì)象

  • 變量 - 屬性
  • 函數(shù) - 方法

定義自定義對(duì)象(通過(guò) class 關(guān)鍵字):

# 自定義的對(duì)象數(shù)據(jù)類型就是面向?qū)ο笾械念悾–lass)的概念
# (object) 表示該類是從哪個(gè)類繼承下來(lái)的。通常,如果沒(méi)有合適的繼承類,就使用object類,這是所有類最終都會(huì)繼承的類
class Student(object):
    # __init__方法的第一個(gè)參數(shù)永遠(yuǎn)是self,表示創(chuàng)建的實(shí)例本身
    # 有了__init__方法,在創(chuàng)建實(shí)例的時(shí)候,就不能傳入空的參數(shù)了,必須傳入與__init__方法匹配的參數(shù),但self不需要傳,Python解釋器自己會(huì)把實(shí)例變量傳進(jìn)去
    def __init__(self, name, score, sex):
        self.name = name
        self.score = score
        在Python中,實(shí)例的變量名如果以__開(kāi)頭,就變成了一個(gè)私有變量(private),只有內(nèi)部可以訪問(wèn),外部不能訪問(wèn)
        self.__sex = sex
    # 和普通的函數(shù)相比,在類中定義的函數(shù)只有一點(diǎn)不同,就是第一個(gè)參數(shù)永遠(yuǎn)是實(shí)例變量self,并且,調(diào)用時(shí),不用傳遞該參數(shù)
    def print_score(self):
        print('%s: %s' % (self.name, self.score))
    # 可對(duì) private 變量增加 getter 和 setter 方法
    def get_sex(self):
        return self.__sex
    def set_sex(self, sex):
        self.__sex = sex
# 根據(jù) Student 類創(chuàng)建出 Student 的實(shí)例
bart = Student('Bart Simpson', 59)
# 給對(duì)象發(fā)消息實(shí)際上就是調(diào)用對(duì)象對(duì)應(yīng)的關(guān)聯(lián)函數(shù),稱之為對(duì)象的方法(Method)
# 要調(diào)用一個(gè)方法,只需要在實(shí)例變量上直接調(diào)用,除了self不用傳遞,其他參數(shù)正常傳入
bart.print_score()
# 可以自由地給一個(gè)實(shí)例變量綁定屬性
bart.age = 15

繼承和多態(tài)

獲取對(duì)象信息

type() —— 判斷對(duì)象類型

type()函數(shù)返回對(duì)應(yīng)的Class類型

type(123)
type('str')
type(None)

type(abs)

比較兩個(gè)變量的type類型是否相同:

type(123)==type(456)
type(123)==int

判斷一個(gè)對(duì)象是否是函數(shù) —— 使用types模塊中定義的常量

import types

def fn():
    pass
    
type(fn)==types.FunctionType ==> True

type(abs)==types.BuiltinFunctionType ==> True

type(lambda x: x)==types.LambdaType ==> True

type((x for x in range(10)))==types.GeneratorType ==> True

isinstance() —— 判斷class的繼承關(guān)系

假設(shè)有繼承關(guān)系:object -> Animal -> Dog -> Husky

a = Animal()
d = Dog()
h = Husky()
isinstance(h, Husky) ==> True
isinstance(h, Dog) ==> True
isinstance(h, Animal) ==> True
isinstance(h, object) ==> True

isinstance(d, Dog) and isinstance(d, Animal) ==> True
isinstance(d, Husky) ==> False

能用type()判斷的基本類型也可以用isinstance()判斷

isinstance('a', str)
isinstance(123, int)

還可以判斷一個(gè)變量是否是某些類型中的一種

# list 或者 tuple
isinstance([1, 2, 3], (list, tuple)) ==> True

dir() —— 獲得對(duì)象的所有屬性和方法

dir()函數(shù),它返回一個(gè)包含字符串的list

dir('123')

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

僅僅把屬性和方法列出來(lái)是不夠的,配合 getattr()setattr() 以及 hasattr() ,我們可以直接操作一個(gè)對(duì)象的狀態(tài):

class MyObject(object):
    def __init__(self):
        self.x = 9
    def power(self):
        return self.x * self.x

obj = MyObject()

屬性:

hasattr(obj, 'x')

hasattr(obj, 'y')

setattr(obj, 'y', 19)

# 試圖獲取不存在的屬性,會(huì)拋出 AttributeError 的錯(cuò)誤
getattr(obj, 'y')

# 可以傳入一個(gè)default參數(shù),如果屬性不存在,就返回默認(rèn)值
getattr(obj, 'y', 404)

方法:

hasattr(obj, 'power')

getattr(obj, 'power')

fn = getattr(obj, 'power')

# 調(diào)用fn()與調(diào)用obj.power()是一樣的
fn()

實(shí)例屬性和類屬性

類本身綁定一個(gè)屬性

class Student(object):
    # name 屬性雖然歸類 Student 所有,但類的所有實(shí)例都可以訪問(wèn)到
    name = 'Student'

相同名稱的實(shí)例屬性將屏蔽掉類屬性,但是當(dāng)刪除實(shí)例屬性后,再使用相同的名稱,訪問(wèn)到的將是類屬性

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

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

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