python編程進(jìn)階之類和對(duì)象用法實(shí)例分析
本文實(shí)例講述了python類和對(duì)象用法。分享給大家供大家參考,具體如下:
前面我們都是用python面向過(guò)程編程,現(xiàn)在來(lái)用python創(chuàng)建類和對(duì)象,面向?qū)ο缶幊?。類和?duì)象是面向?qū)ο缶幊痰膬蓚€(gè)主要方面。類創(chuàng)建一個(gè)新類型,而對(duì)象這個(gè)類的 實(shí)例 。這類似于你有一個(gè)int類型的變量,這存儲(chǔ)整數(shù)的變量是int類的實(shí)例(對(duì)象)。在python中,類和實(shí)例中的變量稱為域,類和實(shí)例中的函數(shù)稱為方法,域和方法都是類和實(shí)例的屬性。
類的定義
在定義類或者它的函數(shù)的時(shí)候,如果沒(méi)有參數(shù)的話,需要把參數(shù)寫(xiě)為self,這樣在外部調(diào)用的時(shí)候能清楚調(diào)用的是哪個(gè)實(shí)例的函數(shù)。這個(gè)self表示的是當(dāng)前的實(shí)例,與C++中的self和Java中的this是一樣的。
空類
#!/usr/bin/python # Filename: simplestclass.py class Person: pass # An empty block p = Person() print p
我們使用class語(yǔ)句后跟類名,創(chuàng)建了一個(gè)新的類。這后面跟著一個(gè)縮進(jìn)的語(yǔ)句塊形成類體。在這個(gè)例子中,我們使用了一個(gè)空白塊,它由pass語(yǔ)句表示。這樣編譯的時(shí)候就會(huì)跳過(guò)。這是一個(gè)空類。
接下來(lái),我們使用類名后跟一對(duì)圓括號(hào)來(lái)創(chuàng)建一個(gè)對(duì)象/實(shí)例。因?yàn)檫@個(gè)類不需要任何的參數(shù),所以創(chuàng)建的時(shí)候也不需要參數(shù)。
$ python simplestclass.py
<__main__.Person instance at 0xf6fcb18c>
打印這個(gè)對(duì)象,我們可以看到這個(gè)對(duì)象所屬的類,以及它的內(nèi)存地址。
__init__函數(shù)
在上面的例子中,我們沒(méi)有寫(xiě)任何東西,但是還是會(huì)有一個(gè)默認(rèn)的構(gòu)造函數(shù)。在python中也有類似構(gòu)造函數(shù)的東西,就是__init__函數(shù)。在創(chuàng)建對(duì)象的時(shí)候會(huì)自動(dòng)調(diào)用這個(gè)函數(shù)。
#!/usr/bin/python # Filename: class_init.py class Person: def __init__(self, name): self.name = name def sayHi(self): print 'Hello, my name is', self.name p = Person('Swaroop') p.sayHi()
輸出:
$ python class_init.py
Hello, my name is Swaroop
當(dāng)新建一個(gè)person對(duì)象時(shí),因?yàn)開(kāi)_init__中需要有name參數(shù),所以需要提供一個(gè)參數(shù)??梢钥吹竭@個(gè)類中有一個(gè)自己的域,在構(gòu)造的時(shí)候把name的值賦給對(duì)象里的name。
可以看到,sayHi并不需要參數(shù),但是在定義函數(shù)時(shí)仍然要有參數(shù)self。
__del__函數(shù)
就如同init方法一樣,還有一個(gè)特殊的方法del,它在對(duì)象消逝的時(shí)候被調(diào)用。相當(dāng)于析構(gòu)函數(shù)。對(duì)象消逝即對(duì)象不再被使用,它所占用的內(nèi)存將返回給系統(tǒng)作它用。但是很難保證這個(gè)方法究竟在什么時(shí)候運(yùn)行。如果你想要指明它的運(yùn)行,你就得使用del語(yǔ)句。代碼例子和下面的在一起。
使用類的變量
Python中所有的類成員(包括數(shù)據(jù)成員)都是公共的,所有的方法都是有效的 。
只有一個(gè)例外:如果你使用的數(shù)據(jù)成員名稱以雙下劃線前綴比如__privatevar,Python的名稱管理體系會(huì)有效地把它作為私有變量。
這樣就有一個(gè)慣例,如果某個(gè)變量只想在類或?qū)ο笾惺褂?,就?yīng)該以單下劃線前綴。而其他的名稱都將作為公共的,可以被其他類/對(duì)象使用。
#!/usr/bin/python # Filename: objvar.py class Person: '''Represents a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' self.name = name print '(Initializing %s)' % self.name # When this person is created, he/she # adds to the population Person.population += 1 def __del__(self): '''I am dying.''' print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print 'Hi, my name is %s.' % self.name def howMany(self): '''Prints the current population.''' if Person.population == 1: print 'There is nobody here.' else: print 'We have %d persons here.' % Person.population swaroop = Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam') kalam.sayHi() kalam.howMany() swaroop.sayHi() swaroop.howMany()
輸出:
$ python objvar.py
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
There is nobody here.
這是一個(gè)很長(zhǎng)的例子。這里,population屬于Person類,因此是一個(gè)類的變量。name變量屬于對(duì)象(它使用self賦值)因此是對(duì)象的變量。
觀察可以發(fā)現(xiàn)init方法用一個(gè)名字來(lái)初始化Person實(shí)例。在這個(gè)方法中,我們讓population增加1,這是因?yàn)槲覀冊(cè)黾恿艘粋€(gè)人。同樣可以發(fā)現(xiàn),self.name的值根據(jù)每個(gè)對(duì)象指定,這表明了它作為對(duì)象的變量的本質(zhì)。
記住,你只能使用self變量來(lái)引用同一個(gè)對(duì)象的變量和方法。這被稱為 屬性引用。
當(dāng)一個(gè)對(duì)象被清除的時(shí)候,del被調(diào)用,人數(shù)減少1并輸出誰(shuí)走了。一開(kāi)始Abdul Kalam被自動(dòng)清除了,后來(lái)Swaroop也被自動(dòng)清除了。清除的順序應(yīng)該跟對(duì)象閑置的時(shí)間有關(guān),當(dāng)閑置時(shí)間達(dá)到某個(gè)值就清除掉。
繼承
python的繼承和C++還有JAVA沒(méi)有什么不同,就是構(gòu)造函數(shù)和其他函數(shù)里記得要在參數(shù)里加上self。函數(shù)的重載也是和C++,JAVA一樣的。
例子:
#!/usr/bin/python # Filename: inherit.py class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = name self.age = age print '(Initialized SchoolMember: %s)' % self.name def tell(self): '''Tell my details.''' print 'Name:"%s" Age:"%s"' % (self.name, self.age), class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print '(Initialized Teacher: %s)' % self.name def tell(self): SchoolMember.tell(self) print 'Salary: "%d"' % self.salary class Student(SchoolMember): '''Represents a student.''' def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print '(Initialized Student: %s)' % self.name def tell(self): SchoolMember.tell(self) print 'Marks: "%d"' % self.marks t = Teacher('Mrs. Shrividya', 40, 30000) s = Student('Swaroop', 22, 75) print # prints a blank line members = [t, s] for member in members: member.tell() # works for both Teachers and Students
輸出:
$ python inherit.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"22" Marks: "75"
schoolmenber是父類,學(xué)生和老師是子類,繼承的方法為在類定義中把參數(shù)設(shè)為schoolmenber??梢钥吹?,當(dāng)我們繼承一個(gè)類的時(shí)候,首先調(diào)用的是父類的構(gòu)造函數(shù),然后才是子類的。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門(mén)與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- python drf各類組件的用法和作用
- python定義類的簡(jiǎn)單用法
- python db類用法說(shuō)明
- Python面向?qū)ο蟪绦蛟O(shè)計(jì)之靜態(tài)方法、類方法、屬性方法原理與用法分析
- Python面向?qū)ο蟪绦蛟O(shè)計(jì)之類和對(duì)象、實(shí)例變量、類變量用法分析
- Python面向?qū)ο笾蓄悾╟lass)的簡(jiǎn)單理解與用法分析
- Python3變量與基本數(shù)據(jù)類型用法實(shí)例分析
- Python 面向?qū)ο笾恈lass和對(duì)象基本用法示例
- python定義類self用法實(shí)例解析
- Python中類似于jquery的pyquery庫(kù)用法分析
- Python上下文管理器類和上下文管理器裝飾器contextmanager用法實(shí)例分析
- 詳細(xì)介紹python類及類的用法
相關(guān)文章
Python實(shí)現(xiàn)文件按照日期命名的方法
這篇文章主要介紹了Python實(shí)現(xiàn)文件按照日期命名的方法,涉及Python針對(duì)文件的遍歷、讀寫(xiě)及時(shí)間操作相關(guān)技巧,需要的朋友可以參考下2015-07-07sklearn中的交叉驗(yàn)證的實(shí)現(xiàn)(Cross-Validation)
這篇文章主要介紹了sklearn中的交叉驗(yàn)證的實(shí)現(xiàn)(Cross-Validation),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02