是否有必要在Python的类中每次都包含__init__作为第一个函数?

NOO*_*OOB 37 python

在Python中,我想知道是否有必要__init__在创建类时包含第一个方法,如下例所示:

class ExampleClass: 

    def __init__(self, some_message): 
        self.message = some_message 
        print "New Class instance created, with message:" 
        print self.message 
Run Code Online (Sandbox Code Playgroud)

另外,我们为什么self要用来调用方法呢?有人可以详细解释"自我"的使用吗?

另外,为什么我们pass在Python中使用语句?

Sus*_*Pal 66

不,没有必要.

例如.

class A(object):
    def f():
        print 'foo'
Run Code Online (Sandbox Code Playgroud)

你当然可以这样使用它:

a = A()
a.f()
Run Code Online (Sandbox Code Playgroud)

实际上,你甚至可以用这种方式定义一个类.

class A:
    pass
Run Code Online (Sandbox Code Playgroud)

但是,定义__init__是一种常见做法,因为类的实例通常存储某种状态信息或数据,并且类的方法提供了一种操作或对该状态信息或数据执行某些操作的方法.__init__允许我们在创建类的实例时初始化此状态信息或数据.

这是一个完整的例子.

class BankAccount(object):
    def __init__(self, deposit):
        self.amount = deposit

    def withdraw(self, amount):
        self.amount -= amount

    def deposit(self, amount):
        self.amount += amount

    def balance(self):
        return self.amount

# Let me create an instance of 'BankAccount' class with the initial
# balance as $2000.
myAccount = BankAccount(2000)

# Let me check if the balance is right.
print myAccount.balance()

# Let me deposit my salary
myAccount.deposit(10000)

# Let me withdraw some money to buy dinner.
myAccount.withdraw(15)

# What's the balance left?
print myAccount.balance()
Run Code Online (Sandbox Code Playgroud)

类的实例始终作为类的方法的第一个参数传递.例如,如果有class A,你有一个实例a = A(),当你打电话a.foo(x, y),Python电话foo(a, x, y)class A自动.(注意第一个参数.)按照惯例,我们将第一个参数命名为self.

  • @BrandonKheang 不,您不需要将类的实例(按照约定命名为“self”)显式传递给每个函数。在调用“a.foo(x, y)”中,“a”是一个隐式参数,它作为第一个参数自动传递给“foo()”。不过,在定义“foo()”时,需要明确提及该类实例的第一个参数,例如“def foo(self, x, y): pass”。 (2认同)

joa*_*uin 8

除了其他答案之外,您问题中的一点尚未解决:

是否有必要在Python中的每个类中包含__init__一个函数?

答案是不.在您需要构造函数的情况下,它可以位于代码的任何位置,尽管传统和逻辑位置是开始.


Luc*_*man 7

您不需要将它放在类中,它是对象构造函数.

如果您希望在对象实例化时自动发生事情,您将需要它.