使用類在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__()
稱為構造函數,當我們從該類創建新對象時,可以使用它來初始化一個或多個屬性:
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