クラスを使用してPythonで新しいオブジェクトを定義する
Pythonが提供する型を使用することに加えて、独自のクラスを宣言したり、クラスからオブジェクトをインスタンス化したりすることができます。
オブジェクトはクラスのインスタンスです。クラスはオブジェクトのタイプです。
次のようにクラスを定義します。
class <class_name>:
# my class
たとえば、Dogクラスを定義しましょう
class Dog:
# the Dog class
クラスはメソッドを定義できます。
class Dog:
# the Dog class
def bark(self):
print('WOF!')
self
メソッドの引数は現在のオブジェクトインスタンスを指しているため、メソッドを定義するときに指定する必要があります。
クラスのインスタンスを作成します。オブジェクト、次の構文を使用します。
roger = Dog()
今roger
タイプDogの新しいオブジェクトです。
実行した場合
print(type(roger))
あなたは得るでしょう<class '__main__.Dog'>
特別なタイプの方法、__init__()
はコンストラクターと呼ばれ、そのクラスから新しいオブジェクトを作成するときに、これを使用して1つ以上のプロパティを初期化できます。
class Dog:
# the Dog class
def __init__(self, name, age):
self.name = name
self.age = age
<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">bark</span>(self):
<span style="color:#66d9ef">print</span>(<span style="color:#e6db74">'WOF!'</span>)</code></pre></div>
We use it in this way:
roger = Dog('Roger', 8)
print(roger.name) # 'Roger'
print(roger.age) # 8
roger.bark() # ‘WOF!’
One important features of classes is inheritance.
We can create an Animal class with a method walk()
:
class Animal:
def walk(self):
print('Walking..')
and the Dog class can inherit from Animal:
class Dog(Animal):
def bark(self):
print('WOF!')
Now creating a new object of class Dog
will have the walk()
method as that’s inherited from Animal
:
roger = Dog()
roger.walk() # 'Walking..'
roger.bark() # 'WOF!'
More python tutorials:
- Introduction to Python
- Installing Python 3 on macOS
- Running Python programs
- Python 2 vs Python 3
- The basics of working with Python
- Python Data Types
- Python Operators
- Python Strings
- Python Booleans
- Python Numbers
- Python, Accepting Input
- Python Control Statements
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionaries
- Python Functions
- Python Objects
- Python Loops
- Python Modules
- Python Classes
- The Python Standard Library
- Debugging Python
- Python variables scope
- Python, accept arguments from command line
- Python Recursion
- Python Nested Functions
- Python Lambda Functions
- Python Closures
- Python Virtual Environments
- Use a GoPro as a remote webcam using Python
- Python, how to create a list from a string
- Python Decorators
- Python Docstrings
- Python Introspection
- Python Annotations
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get the details of a file
- Python, how to check if a file or directory exists
- Python Exceptions
- Python, how to create a directory
- Python, how to create an empty file
- Python, the `with` statement
- Python, create a network request
- Python, installing 3rd party packages using `pip`
- Python, read the content of a file