Anatomia klasy: konstruktor __init__

Wprowadzenie do programowania obiektowego w Pythonie

George Boorman

Curriculum Manager, DataCamp

Metody i atrybuty

  • Metody to definicje funkcji wewnątrz klasy
  • self jako pierwszy argument
  • Atrybuty tworzy się przez przypisanie
  • Odwołania do atrybutów klasy przez self.___
  • Wywoływanie wielu metod może być trudne w utrzymaniu!
class MyClass:
    # function definition in class
    # first argument is self
    def my_method1(self, other_args...):
        # do things here

def my_method2(self, my_attr): # attribute created by assignment self.my_attr = my_attr ...
Wprowadzenie do programowania obiektowego w Pythonie

Konstruktor

  • Dane przypisuje się do obiektu podczas jego tworzenia
  • Konstruktor __init__() jest wywoływany przy każdym tworzeniu obiektu
    • Wywoływany automatycznie dzięki składni __methodname__
class Customer:
    def __init__(self, name):
        # Create the .name attribute and set it to name parameter
        self.name = name
        print("The __init__ method was called")
Wprowadzenie do programowania obiektowego w Pythonie

Konstruktor

# __init__ is implicitly called 
cust = Customer("Lara de Silva")   
print(cust.name)
The __init__ method was called
Lara de Silva
Wprowadzenie do programowania obiektowego w Pythonie

Atrybuty w metodach

class MyClass:
    def my_method1(self, attr1):
        self.attr1 = attr1
        ...

    def my_method2(self, attr2):        
        self.attr2 = attr2
        ...

obj = MyClass() # attr1 created obj.my_method1(val1) # attr2 created obj.my_method2(val2)

Atrybuty w konstruktorze

class MyClass:
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2
        ...

# All attributes are created obj = MyClass(val1, val2)
  • Zazwyczaj należy używać konstruktora
  • Atrybuty są tworzone razem z obiektem
  • Kod łatwiejszy w użyciu i utrzymaniu
Wprowadzenie do programowania obiektowego w Pythonie

Dodaj argumenty

class Customer:
    # Add balance argument
    def __init__(self, name, balance): 

self.name = name # Add the balance attribute self.balance = balance print("The __init__ method was called")
Wprowadzenie do programowania obiektowego w Pythonie

Dodaj parametry

# __init__ is called
cust = Customer("Lara de Silva", 1000)
print(cust.name)
print(cust.balance)
The __init__ method was called
Lara de Silva
1000
Wprowadzenie do programowania obiektowego w Pythonie

Argumenty domyślne

class Customer:
    # Set a default value for balance
    def __init__(self, name, balance=0):
        self.name = name
        # Assign the new attribute
        self.balance = balance
        print("The __init__ method was called")
Wprowadzenie do programowania obiektowego w Pythonie

Argumenty domyślne

# Don't specify the balance explicitly
cust = Customer("Lara de Silva")

print(cust.name) # The balance attribute is created anyway print(cust.balance)
The __init__ method was called
Lara de Silva
0
Wprowadzenie do programowania obiektowego w Pythonie

Dobre praktyki

1. Inicjalizuj atrybuty w __init__()
Wprowadzenie do programowania obiektowego w Pythonie

Dobre praktyki

1. Inicjalizuj atrybuty w __init__()
2. Nazewnictwo

CamelCase dla klas, lower_snake_case dla funkcji i atrybutów

Wprowadzenie do programowania obiektowego w Pythonie

Dobre praktyki

1. Inicjalizuj atrybuty w __init__()
2. Nazewnictwo

CamelCase dla klas, lower_snake_case dla funkcji i atrybutów

3. Zachowaj self jako self
class MyClass:
    # This works but isn't recommended
    def my_method(george, attr):
        george.attr = attr
Wprowadzenie do programowania obiektowego w Pythonie

Dobre praktyki

1. Inicjalizuj atrybuty w __init__()
2. Nazewnictwo

CamelCase dla klas, lower_snake_case dla funkcji i atrybutów

3. self jest self
4. Używaj docstringów
class MyClass:
    """This class does nothing"""
    pass
Wprowadzenie do programowania obiektowego w Pythonie

Czas na ćwiczenia!

Wprowadzenie do programowania obiektowego w Pythonie

Preparing Video For Download...