クラスの構造:属性とメソッド

Pythonによるオブジェクト指向プログラミング入門

George Boorman

Curriculum Manager, DataCamp

Customerクラス

class Customer:

# Code for class goes here
pass
  • class <name>:でクラス定義を開始します
  • class内のコードはインデントします
  • passで「空の」クラスを作成できます
c_one = Customer()
c_two = Customer()
  • ClassName()でClassNameクラスのオブジェクトを作成します
Pythonによるオブジェクト指向プログラミング入門

クラスへのメソッドの追加

class Customer:  

def identify(self, name): print("I am Customer " + name)
  • メソッド定義 = クラス内での関数定義
  • メソッド定義の第1引数にはselfを使用する
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • オブジェクトのメソッドを呼び出す際はselfを省略します
Pythonによるオブジェクト指向プログラミング入門
class Customer:  
    def identify(self, name):
        print("I am Customer " + name)

cust = Customer()
cust.identify("Laura")

selfとは?

  • クラスはテンプレートです
  • selfはメソッドの第1引数にする必要があります
  • selfは(まだ作成されていない)オブジェクトの代替です
  • cust.identify("Laura")はCustomer.identify(cust, "Laura")と解釈されます
Pythonによるオブジェクト指向プログラミング入門

属性が必要な理由

  • OOPはデータとそれを操作するメソッドをまとめます
    • Customerの名前は属性にすべきです

 

$$\text{\Large{属性はメソッド内の代入(=)によって作成されます}}$$

Pythonによるオブジェクト指向プログラミング入門

クラスへの属性の追加

class Customer:  
    # Set the name attribute of an object to new_name
    def set_name(self, new_name):

# Create an attribute by assigning a value # Will create .name when set_name is called self.name = new_name
# Create an object # .name doesn't exist here yet cust = Customer()
# .name is created and set to "Lara de Silva" cust.set_name("Lara de Silva")
print(cust.name)
Lara de Silva
Pythonによるオブジェクト指向プログラミング入門

旧バージョン

class Customer:  



    # Using a parameter
    def identify(self, name):
        print("I am Customer" + name)
cust = Customer()

cust.identify("Eris Odoro") 
I am Customer Eris Odoro 

新バージョン

class Customer:  
   def set_name(self, new_name):
       self.name = new_name

# Using .name from the object it*self* def identify(self): print("I am Customer" + self.name)
cust = Customer()
cust.set_name("Rashid Volkov")
cust.identify()
I am Customer Rashid Volkov
Pythonによるオブジェクト指向プログラミング入門

練習しましょう!

Pythonによるオブジェクト指向プログラミング入門

Preparing Video For Download...