Pythonを用いたオブジェクト指向プログラミング
21593 ワード
Pythonはオブジェクト指向プログラミングをサポートする偉大なプログラミング言語です.
オブジェクト指向プログラミングとは何か
オブジェクトがクラスのインスタンスである間、クラスは概念を表現して、定義する柔軟で、強力なパラダイムです.
なぜオブジェクト指向プログラミングを使うのか?
が定義されている
クラスには、それらに関連付けられた属性とメソッドがあり、特定のクラスの新しい、個々のオブジェクトを作成するときにクラスのインスタンスを持つことができます.
たとえば、上記のダイアグラムでは、フルーツという名前のクラスがあります.
バナナ、リンゴ、パイナップル、イチゴはクラスフルーツのインスタンスです.
インスタンスは、クラスから構築され、実データを含むオブジェクトです.
属性はクラスのクラスまたは特定のインスタンスに関連する特性です.我々の例のように、アップルは属性を持つことができます:色(赤)とテクスチャー(滑らかな)
メソッドはクラスの特定のインスタンスの属性を操作する関数です.私たちのアップルの例では、すべてのバイトでアップルサイズを削減するピースまたは食べる方法にそれを回すカットメソッドを持つことができます.
Pythonでのクラスの生成と定義
Pythonでは関数の定義に似たクラスを作成して定義します.
クラスキーワードから始まり、クラスとコロンの名前が続きます.クラス名は大文字で始まる.クラス定義行がクラス本体の後、右にインデントされます.
class Fruit:
color=" "
texture=" "
ドット表記を使用してクラスインスタンスの属性を設定できます.ドット表記法は、オブジェクト属性を設定するか、またはそれらに関連するメソッドを呼び出すのに使用できます.
apple.color="red"
apple.texture="smooth"
Appleというフルーツインスタンスを作成し、色とテクスチャの属性を設定しました.果物の別のインスタンスを作成することができます別の属性を設定します.pineapple.color="brown"
pineapple.texture="rough"
特殊法
上の例は、クラスとオブジェクトが最も単純な形で、実際のアプリケーションでは役に立ちません.
特殊メソッドは2つのアンダースコア文字で始まり、終了します.
Pythonでクラスをカスタマイズするために特別なメソッドがたくさんあります.
すべてのクラスは特別なメソッドを持ちます.オブジェクトの作成時に必要なオブジェクトプロパティやその他の操作に値を代入するために使用されます.
class Fruit:
def __init__(self,name,color,texture):
self.name=name
self.color=color
self.texture=texture
fruit1=Fruit("apple","red","smooth")
print(fruit1.color)
print(fruit1.texture)
print(fruit1.name)
出力:red
smooth
apple
The self parameter is a reference to the current instance of
the class, and is used to access variables that belong to the
class.
出力は文字列形式で返します.
class Fruit:
def __init__(self,name,color,texture):
self.name=name
self.color=color
self.texture=texture
def __str__(self):
return f"{self.name} is a fruit and its {self.color} in color and its {self.texture}"
fruit2=Fruit("Apple","red","smooth")
print(fruit2)
出力:Apple is a fruit and its red in color and its smooth
フルーツクラスのメソッドの例は以下の通りです.class Fruit:
def __init__(self,name,color,texture):
self.name=name
self.color=color
self.texture=texture
def fruity(self):
return f"{self.name} is {self.color} in color and {self.texture} "
def describe(self,taste):
return f"{self.name} is {taste}"
fruit1=Fruit("apple","red","smooth")
print(fruit1.fruity())
print(fruit1.describe("sweet"))
出力:apple is red in color and smooth
apple is sweet
フルーティーと説明は、我々の果物クラスの方法です.オブジェクト指向プログラミングにはいくつかの重要概念がある.
遺産
オブジェクト指向プログラミングでは、継承の概念を使用すると、オブジェクト間の関係を構築することができますグループ一緒に似た概念とコードの重複を減らす.
親クラスは継承されるクラスです.どんなクラスでも親クラスでありえるので、構文はどんな他のクラスも作成するのと同じです.
子クラスは、別のクラスから継承するクラスです.子クラスは親プロセスからプロパティとメソッドを継承しますが、他のプロパティも追加できます.
子クラスを作成するときに、親クラスの名前がその機能を継承できるようにパラメーターとして設定されます.
To keep the inheritance of the parent's init() function,
add a call to the parent's init() function
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def display(self):
print(self.name+" is "+str(self.age)+" years old")
#child class
class Student(Person):
def __init__(self,name,age,admission,form):
self.admission=admission
self.form = form
# invoking the __init__ of the parent class
Person.__init__(self,name,age)
#Creating an object
Aziz = Student("Abdul Aziz","22","6325",4)
Aziz.display()
Output
>>> Abdul Aziz is 22 years old
上の例から、親クラスの子クラスから子クラスの学生を作成し、親クラスから属性名と年齢とメソッドの表示を継承します.しかし、我々は他の属性の入場とフォームを子供クラスに追加しました.Python also has a super() function that will make the child class inherit all the methods and properties from its parent
カプセル化
この概念は、メソッドと変数へのアクセスを制限することができます.これによりデータが直接変更されることが防止される.Pythonでは、アンダースコアを使用してプライベート属性を表します.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
出力:Selling Price: 900
Selling Price: 900
Selling Price: 1000
上記のプログラムでは、コンピュータのクラスを定義します.我々は、最大価格を外部に設定しようとすると、それは価格を変更するには、セッター機能を使用して、そのプライベート変数の残高Maxprice以来、反映することはできません.
多型
語多形は、多くの形態を有することを意味する.プログラミングにおいて、多形は柔軟性を許す同じ機能名(しかし、異なる活動を実行する)を意味します.
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
出力:New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
我々は、2つのクラスインドとアメリカを作成しました.彼らは似たような構造とメソッドの資本、言語、型を持っていますが、どのような方法でもリンクされていませんが、forループを使用して、共通の国の変数を使って繰り返します.これは多形によって可能となる.
多形概念の理解のためにいくつかのリンクがあります.
https://www.geeksforgeeks.org/polymorphism-in-python/
https://www.programiz.com/python-programming/polymorphism
Reference
この問題について(Pythonを用いたオブジェクト指向プログラミング), 我々は、より多くの情報をここで見つけました https://dev.to/hannahmwende/object-oriented-programming-using-python-4143テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol