Python _init()的目的是什么?

Python _init()的目的是什么?,python,Python,嘿,伙计们,我对\u init\u()做了很多研究,但还是不明白。根据我目前的理解,一个类的所有实例都必须使用它来传递对象参数 我理解self的用法,但无论出于什么原因,我似乎都无法理解\u init()这一点。我们为什么要使用它。它什么时候有用?除了实例化一个类的实例,它还有什么用途 如果所述对象在调用\u init\()之前已经生成,那么它是如何构造的 一般来说,我只是不知道为什么、如何或何时隐藏\u init(),除了用于实例化一个类的实例外,它可以有多个参数,这些参数似乎特定于该类的实例

嘿,伙计们,我对
\u init\u()
做了很多研究,但还是不明白。根据我目前的理解,一个类的所有实例都必须使用它来传递对象参数

我理解
self
的用法,但无论出于什么原因,我似乎都无法理解
\u init()
这一点。我们为什么要使用它。它什么时候有用?除了实例化一个类的实例,它还有什么用途

如果所述对象在调用
\u init\(
)之前已经生成,那么它是如何构造的


一般来说,我只是不知道为什么、如何或何时隐藏
\u init()
,除了用于实例化一个类的实例外,它可以有多个参数,这些参数似乎特定于该类的实例。必须为每个实例调用它?

创建该类型的对象时会调用它,因此您可以执行任何需要的特定于类的初始化操作,而不必记住进行单独的初始化调用。这就是它的用途;这就是它的作用。

我不是这方面的专家,但我知道
\uuuuu init\uuuuuu
方法是每个类或元类的内置方法,它在类实例化中被精确调用

为什么或者为什么要使用
\uuuu init\uuu
方法? 您可以将其用于很多事情,但主要目的是在实例化类实例时将参数传递到该类实例中。实际上,当您执行
类(*args,**kwargs)
时,这些会被传递到
\uuuu init\uuuu
,在那里您可以使用它们,也可以不使用它们

例如:

class Vehicle:

    name = 'vehicle'
    price = None
    canMove = False
    position = 0

    def __init__(self, price, name=None, canMove=False):
        self.name = name if name else self.name
        self.price = price

    def move(self, distance):
        if self.canMove:
            self.position += distance
            return 'The vehicle moved {0} meters'.format(distance)
        return 'The vehicle cannot move'


class Car(Vehicle):
    name = 'car'
    consumption = 100 # (litres per meter)
    fuel = 0 # (litres )
    
    def __init__(self, fuel, consumption=None, *args, **kwargs):
        self.fuel = fuel
        self.consumption = consumption if consumption else self.consumption
        super().__init__(*args, **kwargs)

    def move(self, distance):
        if self.canMove and self.hasFuel():
            available_d = self.fuel / self.consumption
            if distance <= available_d:
                self.fuel -= self.consumption*distance
                self.position += distance
                return 'The vehicle moved {0} meters and has {1} litres left.'.format(distance, self.fuel)
            return 'The vehicle cannot move since it does not have fuel enough'
        return 'The vehicle cannot move since it does not have any fuel'


    def hasFuel(self):
        return True if self.fuel > 0 else False
    
    def giveFuel(self, litres):
        self.fuel += litres
但是,这会引起一个错误,因为
\uuu init\uu
方法需要传递一个强制参数
price
。其余所有字段都是可选字段,但这对于实例化来说是必须的。因此,您可以使用以下方法重试:

myVehicle = Vehicle(10000)
您可以通过以下操作访问刚刚传递的值:

myVehicle.price
您也可以传递其余的元素,但它们不是必需的:

myVehicle2 = Vehicle(10000, name='myVehicle2', canMove=True)
请记住,我们也可以在实例化后将它们分配给我们的第一辆车:

myVehicle.name = 'myVehicle'
现在我们有两种不同的交通工具,一种可以移动,另一种不能。如果我们运行以下命令,可以看到这一点:

myVehicle.move(100)
myVehicle2.move(100)
不会引发错误。如果随后更改第一辆车的属性,无论最初传递给
\uuuuu init\uuuu
的值是多少,该属性都会起作用

它的工作原理与我们的汽车类相似。如果我们使用
Car()

所有这些参数都在
\uuuu init\uuuu
部分中定义,并且
price
标记是必需的,因为它从父类继承

当我们尝试移动汽车时,看看这些值是如何正确工作的:

>>> myCar = Car(price=10000, fuel=150, consumption=10)
>>> myCar.move(10)
'The vehicle cannot move since it does not have any fuel' # we actually have not enabled its canMove property
>>> myCar.canMove = True
>>> myCar.move(10)
'The vehicle moved 10 meters and has 50 litres left.'
>>> myCar.move(1)
'The vehicle moved 1 meters and has 40 litres left.'
>>> myCar.move(30)
'The vehicle cannot move since it does not have fuel enough'

它的目的是初始化属于这个类的特定实例的值。您不必定义一个,但在这种情况下,创建的实例将有一个空的初始状态,这听起来不是很有用。这个问题的哪一部分不清楚?那么这有什么作用呢?这些值可以在其他地方使用吗?我建议您查看一些使用类的Python代码,看看如何使用
\uuuu init\uuu
。那么,它的目的应该是什么呢。例如,查看流行的
请求
库中的。您可以看到每个实例是如何配置某些值的,然后这些值从其他方法中使用的。所有的汽车都有一种颜色。要创建一个新的
汽车
对象
c
,使
c.color
“红色”
,您需要
def\uuu init\uuuuuu(self,color):self.color=color
。然后在
c=Car('red')
之后,
c
将成为
Car
对象,因此
c.color=='red'
在我看来不像你做了“大量研究”。那么需要进行什么样的类初始化呢?如果我将参数分配给实例,它们可以在实例外部使用。就像给一个类的实例分配一个参数x=2。我可以在init之外使用x吗?在你所做的“大量研究”中,你从未见过一个如何使用args to
\uuuu init\uuuu
的例子?我知道写一个关于这个主题的好的、清晰的、简单的答案需要一些时间,但你可能同意我的观点,你的答案根本不是这些。老实说,我只是想学习,这种敌意是不必要的。是的,我有,但我正试图从那些已经做了一段时间的人那里得到更好的例子。很抱歉尝试学习。我喜欢这个答案。让事情变得更清楚。我想今晚当我回家的时候,我会把这些代码弄得乱七八糟,自己学习。非常感谢@AEYES请如果你喜欢它考虑投票,并接受它与检查按钮。如果你愿意的话,也可以问任何进一步的问题。我有一个关于超级电话的问题。此实例中使用了哪些参数。我也很乐意接受它,所以是的,它所做的就是称之为母班。因此,您必须承认所有这些
*参数,**kwargs
,并将它们传递给父
\uuuu init\uuuu
方法,除非您想完全覆盖它<代码>*args、**kwargs
简而言之,是表示类实例化可能接受的所有可能参数(以及一般任何方法或函数)的简化方式。因此,如果我没有这样做,我将无法实例化车辆的价格(我以后仍可以这样做)。我看到基本上您使用的是“Vechile”母类中提供的参数,因此类“Car”继承这些参数并可以以自己的方式使用它们?
>>> Car()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'fuel'
>>> Car(fuel=140)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 10, in __init__
TypeError: __init__() missing 1 required positional argument: 'price'
>>> myCar = Car(price=10000, fuel=150, consumption=10)
>>> myCar.move(10)
'The vehicle cannot move since it does not have any fuel' # we actually have not enabled its canMove property
>>> myCar.canMove = True
>>> myCar.move(10)
'The vehicle moved 10 meters and has 50 litres left.'
>>> myCar.move(1)
'The vehicle moved 1 meters and has 40 litres left.'
>>> myCar.move(30)
'The vehicle cannot move since it does not have fuel enough'