Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

python - Python的__init__和self是做什么的?(What __init__ and self do on Python?)

I'm learning the Python programming language and I've came across something I don't fully understand.

(我正在学习Python编程语言,遇到了一些我不太了解的东西。)

In a method like:

(用类似的方法:)

def method(self, blah):
    def __init__(?):
        ....
    ....

What does self do?

(self做什么的?)

What is it meant to be?

(这是什么意思?)

Is it mandatory?

(它是强制性的吗?)

What does the __init__ method do?

(__init__方法有什么作用?)

Why is it necessary?

(为什么有必要?)

(etc.)

((等等。))

I think they might be OOP constructs, but I don't know very much.

(我认为它们可能是OOP构造,但我不太了解。)

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In this code:

(在此代码中:)

class A(object):
    def __init__(self):
        self.x = 'Hello'

    def method_a(self, foo):
        print self.x + ' ' + foo

... the self variable represents the instance of the object itself.

(... self变量表示对象本身的实例。)

Most object-oriented languages pass this as a hidden parameter to the methods defined on an object;

(大多数面向对象的语言将此作为隐藏参数传递给在对象上定义的方法。)

Python does not.

(Python没有。)

You have to declare it explicitly.

(您必须明确声明它。)

When you create an instance of the A class and call its methods, it will be passed automatically, as in ...

(当创建A类的实例并调用其方法时,它将自动传递,如...)

a = A()               # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument

The __init__ method is roughly what represents a constructor in Python.

(__init__方法大致代表Python中的构造函数。)

When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method.

(调用A() Python会为您创建一个对象,并将其作为第一个参数传递给__init__方法。)

Any additional parameters (eg, A(24, 'Hello') ) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.

(任何其他参数(例如A(24, 'Hello') )也将作为参数传递-在这种情况下,将引发引发异常,因为构造函数不需要它们。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...