Python的__init__和self是做什么的? [英] What __init__ and self do on Python?

查看:145
本文介绍了Python的__init__和self是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

采用类似的方法:

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

self的作用是什么?这是什么意思?是强制性的吗?

What does self do? What is it meant to be? Is it mandatory?

__init__方法有什么作用?为什么有必要? (等等)

What does the __init__ method do? Why is it necessary? (etc.)

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

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

推荐答案

在此代码中:

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

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

... self变量表示对象本身的实例.大多数面向对象的语言将此作为隐藏参数传递给在对象上定义的方法. Python没有.您必须明确声明它.当创建A类的实例并调用其方法时,它将自动传递,如...

... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. 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()               # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument

__init__方法大致代表了Python中的构造函数.调用A()时,Python会为您创建一个对象,并将其作为第一个参数传递给__init__方法.任何其他参数(例如A(24, 'Hello'))也将作为参数传递-在这种情况下,会引发异常,因为构造函数并不期望它们.

The __init__ method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters (e.g., 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.

这篇关于Python的__init__和self是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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