Python類別的繼承(進階5)
1. python中什麼是繼承
python中什麼是繼承:
新類別不必從頭編寫
新類別從現有的類別繼承,就自動擁有了現有類別的所有功能
新類別只需要編寫現有類別缺少的新功能
繼承的好處:
#複用已有程式碼
自動擁有了現有類別的所有功能
只需要寫缺少的新功能
繼承的特點:
子類別和父類別是is關係
python繼承的特點:
總是從某個類別繼承
不要忘記呼叫super().init
2.python中繼承一個類別
class Person(object): def init(self, name, gender): self.name = name self.gender = gender class Teacher(Person): def init(self, name, gender, course): super(Teacher, self).init(name, gender) self.course = course t = Teacher('Alice', 'Female', 'English') print t.name print t.course
3. python中判斷類型
函數isinstance()可以判斷一個變數的類型,既可以用在Python內建的資料型別如str、list、dict,也可以用在我們自訂的類,它們本質上都是資料類型。
class Person(object): def init(self, name, gender): self.name = name self.gender = gender class Student(Person): def init(self, name, gender, score): super(Student, self).init(name, gender) self.score = score class Teacher(Person): def init(self, name, gender, course): super(Teacher, self).init(name, gender) self.course = course t = Teacher('Alice', 'Female', 'English') print isinstance(t, Person) print isinstance(t, Student) print isinstance(t, Teacher) print isinstance(t, object)
4. python中多態
class Person(object): def init(self, name, gender): self.name = name self.gender = gender def whoAmI(self): return 'I am a Person, my name is %s' % self.name class Student(Person): def init(self, name, gender, score): super(Student, self).init(name, gender) self.score = score def whoAmI(self): return 'I am a Student, my name is %s' % self.name class Teacher(Person): def init(self, name, gender, course): super(Teacher, self).init(name, gender) self.course = course def whoAmI(self): return 'I am a Teacher, my name is %s' % self.name import json class Students(object): def read(self): return r'["Tim", "Bob", "Alice"]' s = Students() print json.load(s)
5. python中多重繼承
除了從一個父類別繼承外,Python允許從多個父類別繼承,稱為多重繼承。 Java不能多繼承
class A(object): def init(self, a): print 'init A...' self.a = a class B(A): def init(self, a): super(B, self).init(a) print 'init B...' class C(A): def init(self, a): super(C, self).init(a) print 'init C...' class D(B, C): def init(self, a): super(D, self).init(a) print 'init D...' class Person(object): pass class Student(Person): pass class Teacher(Person): pass class SkillMixin(object): pass class BasketballMixin(SkillMixin): def skill(self): return 'basketball' class FootballMixin(SkillMixin): def skill(self): return 'football' class BStudent(BasketballMixin): pass class FTeacher(FootballMixin): pass s = BStudent() print s.skill() t = FTeacher() print t.skill()
6. python中取得物件資訊
除了用isinstance() 判斷它是否是某種類型的實例外,還有沒有別的方法取得到更多的資訊呢?
首先可以用type() 函數取得變數的類型,它傳回一個Type 物件
#dir() 函數取得變數的所有屬性
dir()傳回的屬性是字串列表,如果已知一個屬性名稱,要取得或設定物件的屬性,就需要用getattr() 和setattr( )函數了
class Person(object): def init(self, name, gender): self.name = name self.gender = gender class Student(Person): def init(self, name, gender, score): super(Student, self).init(name, gender) self.score = score def whoAmI(self): return 'I am a Student, my name is %s' % self.name print type(123) # <type 'int'> s = Student('Bob', 'Male', 88) print s # <class 'main.Student'> print dir(123) # ['abs', 'add', 'and', 'class', 'cmp', 'coerce', 'delattr', 'p', 'pmod', 'doc', 'float', 'floorp', 'format', 'getattribute', 'getnewargs', 'hash', 'hex', 'index', 'init', 'int', 'invert', 'long', 'lshift', 'mod', 'mul', 'neg', 'new', 'nonzero', 'oct', 'or', 'pos', 'pow', 'radd', 'rand', 'rp', 'rpmod', 'reduce', 'reduce_ex', 'repr', 'rfloorp', 'rlshift', 'rmod', 'rmul', 'ror', 'rpow', 'rrshift', 'rshift', 'rsub', 'rtruep', 'rxor', 'setattr', 'sizeof', 'str', 'sub', 'subclasshook', 'truep', 'trunc', 'xor', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] print dir(s) # ['class', 'delattr', 'dict', 'doc', 'format', 'getattribute', 'hash', 'init', 'module', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'gender', 'name', 'score', 'whoAmI'] print getattr(s, 'name') # Bob setattr(s, 'name', 'Adam') print s.name # Adam class Person(object): def init(self, name, gender, **kw): self.name = name self.gender = gender for k, v in kw.iteritems(): setattr(self, k, v) p = Person('Bob', 'Male', age=18, course='Python') print p.age # 18 print p.course #Python
以上是詳解詳細介紹l了Python類別的繼承的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中