gpt4 book ai didi

python - 如何将参数传递给类中的 __init__

转载 作者:行者123 更新时间:2023-12-02 19:28:27 25 4
gpt4 key购买 nike

你好,我正在尝试理解 Python 类中的 __init__。我理解类是如何工作的,但我无法理解一件事这是代码:

class Computer:

def __init__(self, name, cpu, ram, hdd, ssd):
self.name = name
self.cpu = cpu
self.ram = ram
self.hdd = hdd
self.ssd = ssd
def config(self):
print("Configuration of computer is: ", self.name, self.cpu, self.ram, self.hdd, self.ssd )


computer1 = Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB")
computer1.config()

为什么以及如何将参数 Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB") 传递给 __init__(self, name, cpu, ram、hdd、ssd)自动?为什么我们将这些参数写在类括号中而不是像这样单独写:

 computer1.__init__("HP ", "i7 ", "16gb ", "1TB ", "256GB")

代码如何理解计算机括号中写入的参数必须传递给 __init__

最佳答案

因为 __init__ 方法大致代表了 Python 中的构造函数。当您调用 Computer("HP ","i7 ","16gb ","1TB ","256GB") 时,Python 会为您创建一个对象,并将其作为第一个参数传递给 __init__ 方法。任何其他参数(超过您声明的五个)也将作为参数传递 - 在这种情况下会导致引发异常,因为构造函数不需要它们。

关于python - 如何将参数传递给类中的 __init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62156690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com