Python クラスの継承 (上級 5)
1. Python の継承とは
Python の継承とは:
新しいクラスは最初から作成する必要はありません
新しいクラスは既存のクラスから継承します既存のクラスのすべての関数を自動的に所有します
新しいクラスは、既存のクラスに欠けている新しい関数を記述するだけで済みますクラスのすべての関数を持ちます
足りない新しい関数を記述するだけで済みます
特徴継承の特徴:
サブクラスと親クラスは関係性があります
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など)で使用できます、リスト、辞書、またはカスタム クラスでは、これらは本質的にデータ型です。 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 では、1 つの親クラスからの継承に加えて、複数の親クラスからの継承が可能です。これを多重継承と呼びます。 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
以上が詳しい解説ではPythonクラスの継承について詳しく解説していますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond

pythonisnotpurelyLepted; itusesahybridapproachofbytecodecodecodecodecodecodedruntimerttation.1)pythoncompilessourcodeintobytecode、whodythepythonvirtualmachine(pvm).2)

ToconcatenateListsinpythothesheElements、使用:1)Operatortokeepduplicates、2)asettoremoveduplicates、or3)listcomplunting for controloverduplicates、各メトドハスディフェルフェルフェントパフォーマンスアンドソーダーインプリテーション。

pythonisantertedlanguage、useaseofuseandflexibility-butfactingporformantationationsincriticalapplications.1)解釈されたlikepythonexecuteline-by-lineを解釈します

Useforloopswhenthenumberofiterationsisknowninadvance、andwhiloopswheniterationsdependonacondition.1)forloopsareidealforsecenceslikelistoranges.2)


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

Dreamweaver Mac版
ビジュアル Web 開発ツール

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

WebStorm Mac版
便利なJavaScript開発ツール
