Python中的类是否需要__init__构造函数? [英] Is a constructor __init__ necessary for a class in Python?

查看:89
本文介绍了Python中的类是否需要__init__构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. For example,

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 __ 方法向其传递参数?我是班上的新手,我读到的所有内容我都很难理解和混淆.谢谢!

So when I 'call' the class, I pass it the parameters from the __init__ method? I'm new to classes, everything I read I find hard to understand and confusing. Thanks!

编辑1

我发现这个问题有助于解释某些事情,例如 new init 之间的区别,对不起,我不知道如何添加链接,必须删除并粘贴: __init__可以做什么而__new__不能做什么??

I found this question helpful in explaining some things, like the difference between new and init, sorry, I don't know how to add a link, gotta cut and paste: What can `__init__` do that `__new__` cannot?

推荐答案

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

I see a misconception here between a constructor--constructing the object and initializing the object:

Python对 __ new __ __ init __ <的使用/code>?

当您需要控制新实例的创建时,请使用 __ new __ .需要控制新实例的初始化时,请使用 __ init __ .

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.

所以我们在这里必须小心.

So we must be careful here.

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

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

The constructor is not passed to the class, to be precise the result of the constructor (__new__) will be the first argument for every instance method in the class or its sub-classes (note: __new__ works only for new-style classes):

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

看看调用类(创建对象)时会发生什么:

See what happens when you call the class (create the object):

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

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

Calling the class no longer return instance of type A, because we changed the mechanism of the constructor __new__. Actually by doing so you alter the whole meaning of your class, not only, this is pretty much hard to decipher. It's unlikely that you'll switch the type of object during the creating time of that specific object. I hope this sentence makes sense, if not, how will it make sense in your code!

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

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

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

Look what happens when we try to call type_check method:

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

a 不是类 A 的对象,因此基本上您不再可以访问类 A .

a is not an object of class A, so basically you don't have access to class A anymore.

__ init __ 用于初始化对象的状态. __ init __ 不会调用在创建对象后初始化成员的方法,而是通过在创建期间初始化对象的成员来解决此问题,因此,如果您有一个名为 name ,并且您要在创建类时初始化 name ,而不是调用额外的方法 init_name('name'),您肯定会为此使用 __ init __ .

__init__ is used to initialize the object's state. Instead of calling methods that will initialize the object's members after it's created, __init__ solves this issue by initializing the object's members during creation time, so if you have a member called name inside a class and you want to initialize name when you create the class instead of calling an extra method init_name('name'), you would certainly use __init__ for this purpose.

因此,当我调用"该类时,是否通过 __ init __ 方法向其传递参数?

调用类时,是否将参数传递给 __ init __ 方法?

When you call the class, you pass the parameters (to) __init__ method?

无论您传递类的任何参数,所有参数都将传递给 __ init __ ,并自动为您添加一个附加参数,这是通常称为 self 的隐含对象(实例本身),将始终作为最左参数由Python自动传递:

Whatever arguments you pass the class, all the parameters will be passed to __init__ with one additional parameter added automatically for you which is the implied object usually called self (the instance itself) that will be passed always as the left-most argument by Python automatically:

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 __ 适用于

Note: __init__ works for both classic classes and new style classes. Whereas, __new__ works only for new-style classes.

这篇关于Python中的类是否需要__init__构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆