0
0

Python 基本編

Last updated at Posted at 2024-07-20

Python 基本編

Pythonの基本的な構文とデータ構造について解説します。
基本編では、関数、変数、リスト、辞書などの基本的な概念から、クラス、継承、ポリモーフィズムといったオブジェクト指向の概念まで、幅広くカバーします。

目次

  1. 関数(Function)
  2. 変数(Variable)
  3. 引数(Argument)
  4. リスト(List)
  5. タプル(Tuple)
  6. 辞書(Dictionary)
  7. 集合(Set)
  8. オブジェクト(Object)
  9. クラス(Class)
  10. メソッド(Method)
  11. インスタンス(Instance)
  12. コンストラクタ(Constructor)
  13. 継承(Inheritance)
  14. 多重継承(Multiple Inheritance)
  15. ポリモーフィズム(Polymorphism)
  16. 抽象クラス(Abstract Class)
  17. インターフェース(Interface)
  18. エンカプセレーション(Encapsulation)
  19. アクセサ(Accessor)
  20. ミューテータ(Mutator)
  21. プロパティ(Property)
  22. 静的メソッド(Static Method)
  23. クラスメソッド(Class Method)
  24. デコレータ(Decorator)
  25. モジュール(Module)
  26. パッケージ(Package)
  27. 名前空間(Namespace)
  28. 例外(Exception)
  29. 例外処理(Exception Handling)
  30. スタックトレース(Stack Trace)
  31. ロギング(Logging)
  32. ユニットテスト(Unit Test)
  33. テスト駆動開発(Test-Driven Development)

1. 関数(Function)
関数は、特定のタスクを実行するためのコードのブロックです。関数を定義するには def キーワードを使います。

Function.py
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))  # Output: Hello, Alice!

2. 変数(Variable)
変数は、データを保存するための名前付きの記憶場所です。Pythonでは、変数は特定の型を持たず、動的に型が決まります。

Variable.py
x = 10
name = "Alice"
is_active = True

print(x)         # Output: 10
print(name)      # Output: Alice
print(is_active) # Output: True

3. 引数(Argument)
引数は、関数に渡される入力値です。関数は引数を使って処理を行い、結果を返します。

Argument.py
def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # Output: 8

4. リスト(List)
リストは、複数の要素を格納できるデータ構造で、順序付きでミュータブル(変更可能)です。

List.py
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'orange']

5. タプル(Tuple)
タプルは、リストと似ていますが、イミュータブル(変更不可)です。

Tuple.py
colors = ("red", "green", "blue")
print(colors)  # Output: ('red', 'green', 'blue')

6. 辞書(Dictionary)
辞書は、キーと値のペアを格納するデータ構造です。キーはユニークでなければならず、ハッシュ可能である必要があります。

Dictionary.py
colors = ("red", "green", "blue")
print(colors)  # Output: ('red', 'green', 'blue')

7. 集合(Set)
集合は、ユニークな要素を格納するデータ構造です。重複を許さず、順序も保持しません。

Set.py
unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers)  # Output: {1, 2, 3, 4}

8. オブジェクト(Object)
集合は、ユニークな要素を格納するデータ構造です。重複を許さず、順序も保持しません。

Object.py
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return "Woof!"

dog = Dog("Buddy")
print(dog.name)  # Output: Buddy
print(dog.bark())  # Output: Woof!

9. クラス(Class)
クラスは、オブジェクトの設計図です。クラスは属性とメソッドを持つことができます。

Class.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

person = Person("Alice", 25)
print(person.greet())  # Output: Hello, my name is Alice and I am 25 years old.

10. メソッド(Method)
クラスは、オブジェクトの設計図です。クラスは属性とメソッドを持つことができます。

Method.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

person = Person("Alice", 25)
print(person.greet())  # Output: Hello, my name is Alice and I am 25 years old.

11. インスタンス(Instance)
クラスは、オブジェクトの設計図です。クラスは属性とメソッドを持つことができます。

Instance.py
class Animal:
    def __init__(self, species):
        self.species = species

lion = Animal("Lion")
print(lion.species)  # Output: Lion

12. コンストラクタ(Constructor)
コンストラクタは、オブジェクトが生成されるときに呼び出されるメソッドです。Pythonでは、init メソッドがコンストラクタです。

Constructor.py
class Book:
    def __init__(self, title):
        self.title = title

book = Book("1984")
print(book.title)  # Output: 1984

13. 継承(Inheritance)
継承は、クラスが他のクラスの属性とメソッドを引き継ぐメカニズムです。

Inheritance.py
class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def bark(self):
        return "Woof!"

dog = Dog("Buddy")
print(dog.name)  # Output: Buddy
print(dog.bark())  # Output: Woof!

14. 多重継承(Multiple Inheritance)
継承は、クラスが他のクラスの属性とメソッドを引き継ぐメカニズムです。

Multiple Inheritance.py
class Animal:
    def eat(self):
        return "Eating"

class Mammal:
    def walk(self):
        return "Walking"

class Dog(Animal, Mammal):
    def bark(self):
        return "Woof!"

dog = Dog()
print(dog.eat())  # Output: Eating
print(dog.walk())  # Output: Walking
print(dog.bark())  # Output: Woof!

15. ポリモーフィズム(Polymorphism)
ポリモーフィズムは、同じインターフェースを使用して異なる型のオブジェクトを操作する能力です。

Polymorphism.py
class Cat:
    def sound(self):
        return "Meow"

class Dog:
    def sound(self):
        return "Woof"

def make_sound(animal):
    return animal.sound()

cat = Cat()
dog = Dog()
print(make_sound(cat))  # Output: Meow
print(make_sound(dog))  # Output: Woof

print(dog.bark())  # Output: Woof!

16. 抽象クラス(Abstract Class)
ポリモーフィズムは、同じインターフェースを使用して異なる型のオブジェクトを操作する能力です。

Abstract Class.py
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Cat(Animal):
    def sound(self):
        return "Meow"

cat = Cat()
print(cat.sound())  # Output: Meow

17. インターフェース(Interface)
Pythonでは、インターフェースを明示的に定義する構文はありませんが、抽象基底クラス(ABC)を使用して同様の機能を実現できます。

Interface.py
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

rect = Rectangle(3, 4)
print(rect.area())  # Output: 12

18. エンカプセレーション(Encapsulation)
エンカプセレーションは、データとメソッドをクラス内に隠蔽する概念です。Pythonでは、先頭にアンダースコアをつけることで非公開の属性やメソッドを示します。

Encapsulation.py
class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_name(self):
        return self._name

    def get_age(self):
        return self._age

person = Person("Alice", 25)
print(person.get_name())  # Output: Alice
print(person.get_age())  # Output: 25

19. アクセサ(Accessor)
アクセサは、オブジェクトの属性にアクセスするためのメソッドです。Pythonでは、通常「getter」として実装されます。

Accessor.py
class Person:
    def __init__(self, name):
        self._name = name

    def get_name(self):
        return self._name

person = Person("Alice")
print(person.get_name())  # Output: Alice

20. ミューテータ(Mutator)
ミューテータは、オブジェクトの属性を変更するためのメソッドです。Pythonでは、通常「setter」として実装されます。

Mutator.py
class Person:
    def __init__(self, name):
        self._name = name

    def set_name(self, name):
        self._name = name

person = Person("Alice")
person.set_name("Bob")
print(person.get_name())  # Output: Bob

21. プロパティ(Property)
プロパティは、属性に対するゲッターとセッターを定義するためのPythonの機能です。property デコレータを使用します。

Property.py
class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

person = Person("Alice")
print(person.name)  # Output: Alice
person.name = "Bob"
print(person.name)  # Output: Bob

22. 静的メソッド(Static Method)
静的メソッドは、インスタンスに依存しないメソッドです。staticmethod デコレータを使用して定義します

Static Method.py
class Math:
    @staticmethod
    def add(a, b):
        return a + b

print(Math.add(3, 5))  # Output: 8

23. クラスメソッド(Class Method)
クラスメソッドは、クラス自体に対して操作を行うメソッドです。classmethod デコレータを使用して定義します。

Class Method.py
class Person:
    count = 0

    def __init__(self, name):
        self.name = name
        Person.count += 1

    @classmethod
    def get_count(cls):
        return cls.count

print(Person.get_count())  # Output: 0
p1 = Person("Alice")
print(Person.get_count())  # Output: 1

24. デコレータ(Decorator)
デコレータは、既存の関数やメソッドを修正または拡張するための関数です。デコレータは、関数に新しい機能を追加するために使用されます。

Decorator.py
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# Output:
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.

25. モジュール(Module)
モジュールは、Pythonファイルであり、関連するコードをまとめて再利用可能にするために使用されます。別のPythonファイルからインポートすることで使用できます。

Module.py
# example_module.py
def greet(name):
    return f"Hello, {name}!"

# main.py
import example_module

print(example_module.greet("Alice"))  # Output: Hello, Alice!

26. パッケージ(Package)
パッケージは、複数のモジュールをまとめるためのディレクトリです。パッケージ内には init.py ファイルが必要です。

Package.py
# package_example/__init__.py
# (空のファイル)

# package_example/module1.py
def greet(name):
    return f"Hello, {name}!"

# main.py
from package_example import module1

print(module1.greet("Alice"))  # Output: Hello, Alice!

27. 名前空間(Namespace)
名前空間は、識別子(変数名、関数名など)の範囲を定義するコンテキストです。Pythonでは、モジュールやクラス、関数がそれぞれの名前空間を持ちます。

Namespace.py
# module1.py
def func():
    print("This is module1")

# module2.py
def func():
    print("This is module2")

# main.py
import module1
import module2

module1.func()  # Output: This is module1
module2.func()  # Output: This is module2

28. 例外(Exception)
例外は、エラーが発生したことを示すイベントです。Pythonでは、例外はオブジェクトであり、try、except ブロックを使用して処理します。

Exception.py
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")  # Output: Error: division by zero

29. 例外処理(Exception Handling)
例外処理は、エラーが発生した場合にプログラムが適切に対応できるようにするメカニズムです。

Exception Handling.py
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This will always execute.")
# Output:
# Cannot divide by zero!
# This will always execute.

30. スタックトレース(Stack Trace)
スタックトレースは、例外が発生したときの関数呼び出しの履歴です。例外のデバッグに役立ちます。

Stack Trace.py
def func1():
    func2()

def func2():
    raise Exception("An error occurred")

try:
    func1()
except Exception as e:
    import traceback
    traceback.print_exc()
# Output:
# Traceback (most recent call last):
#   File "main.py", line 9, in <module>
#     func1()
#   File "main.py", line 2, in func1
#     func2()
#   File "main.py", line 5, in func2
#     raise Exception("An error occurred")
# Exception: An error occurred

31. ロギング(Logging)
ロギングは、プログラムの動作を記録するための仕組みです。Pythonの logging モジュールを使用してログを記録できます。

Logging.py
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

logger.info("This is an info message")
logger.error("This is an error message")
# Output:
# INFO:__main__:This is an info message
# ERROR:__main__:This is an error message

32. ユニットテスト(Unit Test)
ユニットテストは、コードの特定の部分(単位)が正しく動作するかを確認するためのテストです。Pythonの unittest モジュールを使用してテストを作成できます。

Unit Test.py
import unittest

def add(a, b):
    return a + b

class TestAddFunction(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

if __name__ == '__main__':
    unittest.main()

33. テスト駆動開発(Test-Driven Development)
テスト駆動開発(TDD)は、まずテストを作成し、そのテストをパスするためのコードを実装する開発手法です。これにより、コードの品質を保つことができます。

Test-Driven Development.py
import unittest

def multiply(a, b):
    return a * b

class TestMultiplyFunction(unittest.TestCase):
    def test_multiply(self):
        self.assertEqual(multiply(2, 3), 6)
        self.assertEqual(multiply(-1, 1), -1)

if __name__ == '__main__':
    unittest.main()

最後までお読みいただきありがとうございました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0