__init__ 和 self 在 Python 中做什么? [英] What __init__ and self do in Python?

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

问题描述

我正在学习 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 变量表示对象本身的实例.大多数面向对象的语言将 this 作为隐藏参数传递给对象上定义的方法;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.

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

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