繁体   English   中英

arguments 如何在类中传递给 __init__

[英]how arguments are passed to __init__ in classes

您好,我想了解 Python 中的 class 中的__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()

为什么以及如何将 arguments Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB")自动传递给__init__(self, name, cpu, ram, hdd, ssd) ?我们为什么要写这个arguments 在 class 括号中,而不是像这样分开:

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

代码如何理解必须将计算机括号中编写的 arguments 传递给__init__

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

这就是 python 的工作原理。 可能是这样设计的,因为某些类/结构是用纯 C 编写的。

例如。 当您想实现自定义 class 并为其实现len() function 时,您可以通过调用len(instance_of_your_class)来获取它的长度。 然后你所要做的就是在你的 class 中实现方法__len__()
另一方面,您在 python 中有 class list 这个 class 在 C 中实现,因为它必须非常快。 然后,当您调用len(instance_of_list)时,解释将调用__len__ ,它将在 C 中调用等效的 function。

这种设计带来了很多好处。 一个例子是方法__getitem__ 您实现了这样您就可以使用instalce_of_class[2]获取元素。 但它也使您能够使用in ( if value in instance_of_class )。

你可以阅读类似的方法。 dunder行话中,它们是笨拙的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM