Python中的类是否需要构造函数init?

2024-10-05 11:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我读到构造函数就像传递给类的第一个参数,这对我来说很有意义,因为参数似乎是通过__init__方法传递给类的。例如

class NewsStory(object):
    def __init__(self, guid, title, subject, summary, link):
        self.guid = guid
        self.title = title
        self.subject = subject
        self.summary = summary
        self.link = link

    def get_guid(self):
        return self.guid

    def get_title(self):
        return self.title

    def get_subject(self):
        return self.subject

    def get_summary(self):
        return self.summary

    def get_link(self):
        return self.link
firstStory = NewsStory('Globally Unique Identifier', \
    'first_title','first_subject','This is an example \
    sumary','example_link@something.com')

print firstStory.get_guid() # prints Globally Unique Identifier

所以当我“调用”这个类时,我从__init__方法向它传递参数?我是新来上课的,我读到的每一件事都让我觉得难以理解和困惑。谢谢!

编辑1

我发现这个问题有助于解释一些事情,例如newin I t之间的区别,对不起,我不知道如何添加链接,必须剪切并粘贴:What can `__init__` do that `__new__` cannot?


Tags: 方法self参数getreturntitleinitdef
3条回答

我在这里看到了构造函数之间的一个误解——构造对象和初始化对象:

Python's use of ^{} and ^{}?

Use __new__ when you need to control the creation of a new instance. Use __init__ when you need to control initialization of a new instance.

所以我们在这里一定要小心。

I read that the constructor is like the first argument passed to the class, which makes sense to me since the parameters seem to be passed to the class via the __init__ method.

构造函数不会传递给类,准确地说,构造函数(__new__)的结果将是类或其子类中每个实例方法的第一个参数(注意:__new__仅适用于新样式的类):

class A:
    def __new__(self):
            return 'xyz'

查看调用类(创建对象)时发生的情况:

>>> A()
'xyz'
>>> type(A())
<class 'str'>

调用类不再返回类型为A的实例,因为我们更改了构造函数__new__的机制。实际上,这样做不仅改变了类的全部含义,而且很难破译。在创建特定对象的过程中,不太可能切换对象的类型。我希望这句话有意义,如果没有,它将如何在您的代码意义!

class A:
    def __new__(self):
            return 'xyz'

    def type_check(self):
            print(type(self))

看看当我们试图调用type_check方法时会发生什么:

>>> a = A()
>>> a
'xyz'
>>> a.type_check()
AttributeError: 'str' object has no attribute 'type_check'

a不是类A的对象,因此基本上您不再有权访问类A

__init__用于初始化对象的状态。与其调用在创建后初始化对象成员的方法,__init__通过在创建期间初始化对象的成员来解决这个问题,所以如果在类中有一个名为name的成员,并且希望在创建类时初始化name,而不是调用额外的方法init_name('name'),您肯定会为此目的使用__init__

So when I 'call' the class, I pass it the parameters from the __init__ method?

调用类时,传递参数__init__方法?

无论您传递类的参数是什么,所有参数都将传递给__init__,并自动为您添加一个额外的参数,这是Python通常称为self(实例本身)的隐含对象,它将始终作为最左的参数自动传递:

class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b 

        A(  34,  35) 
 self.a = 34 |    |  
             |    | 
             |    | self.b = 35  
  init(self, a,   b)
        |
        |
        | 
       The instance that you created by calling the class A() 

注意:__init__对两者都有效。然而,__new__只适用于新样式的类。

Python类的工作方式与其他语言中的类略有不同。 例如,python中没有私有属性。只是命名约定暗示方法或成员变量不打算用于公共用途(前导_)。

虽然每个类都必须具有属性__new____init__,这两个属性共同构建了其他语言可能调用的构造函数,但基本python类实现了这些方法。如果不需要,您不必重写它们。

这很好:

class A:
   def hello(self):
        print('Hello, World')

a = A()
a.hello()

在python中,__new__(cls, ...)首先用于创建请求的cls的类实例。然后将新创建的实例作为self传递给__init__(self, ...)

__new____init__方法都接收传递给构造表达式的参数。这就是python调用m = MyClas(1, 2, 3)的方式。

class A:
    def __new__(cls, *args, **kwargs):
        print('In __new__')
        print(args)
        print(kwargs)
        return object.__new__(cls) # create a new object of type cls

    def __init__(self, *args, **kwargs):
        print('In __init__')
        print(args)
        print(kwargs)


a = A(1, 2, c=3)

结果:

In __new__
(1, 2)
{'c': 3}
In __init__
(1, 2)
{'c': 3}

不,构造函数只是用来构造对象的方法。任何地方都没有经过。相反,它self的对象会自动传递给类的所有方法。

如果您没有要构造的内容,则不需要构造函数,但通常您在开始时有一些事情要做。

相关问题 更多 >

    热门问题