简体   繁体   English

Python “自我”约定 __init__ 与方法

[英]Python “self” convention __init__ vs method

class MyClass(object):
   def __init__(self):
       self.var = "hi"

   def some_method(self):
       print self.var

#for the example below
myClass= MyClass()

So I understand that the following statements are equivelent.所以我理解以下陈述是等价的。

myClass.some_method()
MyClass.some_method(myClass)

It takes object and passes it as the first argument self to some_method .它采用object并将其作为第一个参数self传递给some_method

But when I do:但是当我这样做时:

myClass= MyClass()

How does this flow work?这个流程是如何工作的?

I am assuming its slightly different, and some magic happens behind the scenes (someone has some memory to allocate).我假设它略有不同,并且在幕后发生了一些魔术(有人要分配一些 memory)。

How does that translate to __init__(self) ?这如何转化为__init__(self) What is passed to __init__ MyClass ?传递给__init__ MyClass的内容是什么?

myClass= MyClass() calls MyClass.__new__ method to create an instance of MyClass . myClass= MyClass()调用MyClass.__new__方法来创建MyClass的一个实例。 After that MyClass.__init__ is called with this instance as first argument.之后MyClass.__init__以这个实例作为第一个参数被调用。

See the doc object.__new__ :请参阅文档object.__new__

object. object。 __new__ (cls[, ...]) __new__ (cls[, ...])

Called to create a new instance of class cls.调用以创建 class cls 的新实例。

object. object。 __init__ (self[, ...]) __init__ (self[, ...])

Called when the instance is created.创建实例时调用。

__init__() method is called immediately after an instance of the class is created.在创建 class 的实例后立即调用__init__()方法。

Dive into Python - Initializing and Coding Classes 深入了解 Python - 初始化和编码类

MyClass() creates a brand new object, which is passed to __init__(self) as the parameter self . MyClass()创建一个全新的 object,它作为参数self传递给__init__(self) You can then set up whatever fields you want on self , and then MyClass() returns it.然后,您可以在self上设置您想要的任何字段,然后MyClass()返回它。

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

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