我读到构造函数就像传递给类的第一个参数,这对我来说很有意义,因为参数似乎是通过__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
我发现这个问题有助于解释一些事情,例如new和in I t之间的区别,对不起,我不知道如何添加链接,必须剪切并粘贴:What can `__init__` do that `__new__` cannot?
我在这里看到了构造函数之间的一个误解——构造对象和初始化对象:
Python's use of ^{} and ^{}?
所以我们在这里一定要小心。
构造函数不会传递给类,准确地说,构造函数(
__new__
)的结果将是类或其子类中每个实例方法的第一个参数(注意:__new__
仅适用于新样式的类):查看调用类(创建对象)时发生的情况:
调用类不再返回类型为
A
的实例,因为我们更改了构造函数__new__
的机制。实际上,这样做不仅改变了类的全部含义,而且很难破译。在创建特定对象的过程中,不太可能切换对象的类型。我希望这句话有意义,如果没有,它将如何在您的代码意义!看看当我们试图调用
type_check
方法时会发生什么:a
不是类A
的对象,因此基本上您不再有权访问类A
。__init__
用于初始化对象的状态。与其调用在创建后初始化对象成员的方法,__init__
通过在创建期间初始化对象的成员来解决这个问题,所以如果在类中有一个名为name
的成员,并且希望在创建类时初始化name
,而不是调用额外的方法init_name('name')
,您肯定会为此目的使用__init__
。调用类时,传递参数
__init__
方法?无论您传递类的参数是什么,所有参数都将传递给
__init__
,并自动为您添加一个额外的参数,这是Python通常称为self
(实例本身)的隐含对象,它将始终作为最左的参数自动传递:注意:
__init__
对两者都有效。然而,__new__
只适用于新样式的类。Python类的工作方式与其他语言中的类略有不同。 例如,python中没有私有属性。只是命名约定暗示方法或成员变量不打算用于公共用途(前导
_
)。虽然每个类都必须具有属性
__new__
和__init__
,这两个属性共同构建了其他语言可能调用的构造函数,但基本python类实现了这些方法。如果不需要,您不必重写它们。这很好:
在python中,
__new__(cls, ...)
首先用于创建请求的cls
的类实例。然后将新创建的实例作为self
传递给__init__(self, ...)
。__new__
和__init__
方法都接收传递给构造表达式的参数。这就是python调用m = MyClas(1, 2, 3)
的方式。结果:
不,构造函数只是用来构造对象的方法。任何地方都没有经过。相反,它
self
的对象会自动传递给类的所有方法。如果您没有要构造的内容,则不需要构造函数,但通常您在开始时有一些事情要做。
相关问题 更多 >
编程相关推荐