メインコンテンツにスキップ
モジュール 7 · レッスン 1 / 4コース内の 25/36~14 min
モジュールのレッスン (1/4)

クラスとインスタンス

クラスは、データ (属性) を持つオブジェクトを作成するための設計図です。 そして行動(方法)。 インスタンスは、から作成された具体的なオブジェクトです。 クラス。

最小限の構文

Python
class Cane:
    def __init__(self, nome, eta):
        self.nome = nome
        self.eta = eta

    def abbaia(self):
        return f"{self.nome} dice WOOF!"

# creazione di istanze
fido = Cane("Fido", 3)
luna = Cane("Luna", 5)

fido.nome       # 'Fido'
fido.abbaia()   # 'Fido dice WOOF!'

__init__: 「コンストラクター」

__init__ メソッドは、 インスタンス (Cane("Fido", 3))。属性を初期化するために使用されます。

技術的には、これはコンストラクターではありません (オブジェクトはすでに によって作成されています) __new__) ですが、初期状態を設定する場所です。

self: 最初のパラメータ

self は、メソッドが呼び出されたインスタンスへの参照です。それは 規則 (キーワードではありません) であり、常にインスタンスの最初のパラメータです メソッド。

Python
fido.abbaia()
# equivalente a Cane.abbaia(fido)
# Python passa fido come self automaticamente

インスタンス属性とクラス属性

Python
class Cane:
    specie = "Canis familiaris"   # attributo di CLASSE (condiviso)

    def __init__(self, nome):
        self.nome = nome           # attributo di ISTANZA (per ognuno)

fido = Cane("Fido")
luna = Cane("Luna")

fido.nome       # 'Fido'        (istanza)
luna.nome       # 'Luna'        (istanza)
fido.specie     # 'Canis familiaris'  (cercato sulla classe)
Cane.specie     # 'Canis familiaris'

複数のメソッドと状態

Python
class Contatore:
    def __init__(self, inizio=0):
        self.valore = inizio

    def incrementa(self, di=1):
        self.valore += di

    def reset(self):
        self.valore = 0

c = Contatore()
c.incrementa()
c.incrementa(di=5)
c.valore       # 6
c.reset()
c.valore       # 0

あなたの番です

運動#python.m7.l1.e1
試行回数: 0読み込み中…

属性を格納するクラス `Point` を __init__(self, x, y) で定義します。 x^2 + y^2 の平方根を返すメソッド ` distance_from_origin` を追加します。 `p = Point(3, 4)` を作成し、`p. distance_from_origin()` を評価します。

エディターを読み込み中…
ヒントを表示

math.sqrt(self.x ** 2 + self.y ** 2)

3 回の試行後に解決策が利用可能になります

復習演習

運動#python.m7.l1.e2
試行回数: 0読み込み中…

__init__(self, Balance=0) を使用して `BankAccount` を定義し、self.balance を変更するメソッド `deposit(amount)`、`withdraw(amount)` を定義します。 「a = BankAccount(100)」を作成し、50 入金、30 を引き出します。「a.balance」を評価します。

エディターを読み込み中…
ヒントを表示

自己残高 += 入金額。

3 回の試行後に解決策が利用可能になります

追加の課題

運動#python.m7.l1.e3
試行回数: 0読み込み中…

Define a class `Rectangle` with a constructor `__init__(self, width, height)` to set width and height, and a method `area(self)` that returns the product of width and height. Instantiate a rectangle with width `4` and height `5` storing it in `rect`, and evaluate `rect.area()`.

エディターを読み込み中…
ヒントを表示

area(self) 内の属性にアクセスするには、必ず self を使用してください。

3 回の試行後に解決策が利用可能になります