geekdoc-python-zh/docs/pythonland/22.md

73 lines
2.9 KiB
Markdown
Raw Permalink Normal View History

2024-03-03 22:54:39 +08:00
# Python 构造函数
> 原文:[https://python.land/objects-and-classes/python-constructors](https://python.land/objects-and-classes/python-constructors)
我们现在来看一个特殊的 [Python 函数](https://python.land/introduction-to-python/functions),它是大多数类的一部分:Python 构造函数。构造函数是在创建对象时自动调用的函数。构造函数也可以有选择地接受参数,就像常规函数一样。
目录
* [默认构造函数](#The_default_constructor "The default constructor")
* [创建自己的 Python 构造函数](#Creating_your_own_Python_constructor "Creating your own Python constructor")
## 默认构造函数
当从一个类创建一个对象时,看起来我们在调用一个函数:
```py
car = Car()
```
嗯…这不仅仅看起来像是我们在调用一个函数,我们实际上是在调用一个函数!我们不必定义这个方法,它被称为构造函数。它构造并初始化对象。每个类默认都有一个,叫做`__init__`,即使我们自己没有定义。这与[继承](https://python.land/objects-and-classes/python-inheritance)有关,你很快就会了解到。
你用过`str()`函数把数字转换成字符串吗?或者是将字符串转换成数字的`int()`函数?
Thank you for reading my tutorials. I write these in my free time, and it requires a lot of time and effort. I use ads to keep writing these *free* articles, I hope you understand! **Support me by disabling your adblocker on my website** or, alternatively, **[buy me some coffee](https://www.buymeacoffee.com/pythonland)**. It's much appreciated and allows me to keep working on this site!
```py
>>> 'a' + str(1)
'a1'
>>> int('2') + 2
4
```
你在这里所做的,是通过调用类`str`和`int`的构造函数来创建类型`str`和`int`的新对象。
## 创建自己的 Python 构造函数
我们可以覆盖`__init__`方法,通过接受参数赋予它额外的能力。让我们使用自定义构造函数重新定义`Car`类:
```py
class Car:
def __init__(self, started = False, speed = 0):
self.started = started
self.speed = speed
def start(self):
self.started = True
print("Car started, let's ride!")
def increase_speed(self, delta):
if self.started:
self.speed = self.speed + delta
print("Vrooooom!")
else:
print("You need to start the car first")
def stop(self):
self.speed = 0
```
我们的定制 Python 构造函数有带默认值的命名参数[,所以我们可以用多种方式创建类`Car`的实例:](https://python.land/introduction-to-python/functions#Default_values_and_named_parameters)
```py
>>> c1 = Car()
>>> c2 = Car(True)
>>> c3 = Car(True, 50)
>>> c4 = Car(started=True, speed=40)
```
你可能已经注意到了一个缺陷:我们现在可以创造一辆新车,它不启动,但无论如何都要设定它的速度。现在,我们就到此为止吧。