gpt4 book ai didi

python - Python 中的类是否需要构造函数 __init__?

转载 作者:太空狗 更新时间:2023-10-30 02:28:03 24 4
gpt4 key购买 nike

我读到构造函数就像传递给类的第一个参数,这对我来说很有意义,因为参数似乎是通过 __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

我发现这个问题有助于解释一些事情,比如 newinit 之间的区别,抱歉,我不知道如何添加链接,得删了并粘贴:What can `__init__` do that `__new__` cannot?

最佳答案

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

Python's use of __new__ and __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.

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

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__ 并自动为您添加一个额外的参数,即通常称为 self 的隐含对象(实例本身)将始终作为 最左边的参数 由 Python 自动传递:

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__ 适用于 classic classes and new style classes .然而,__new__ 仅适用于新式类。

关于python - Python 中的类是否需要构造函数 __init__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38280526/

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