在Python中,每次在类中都必须将__init__作为第一个函数吗?
在Python中,我想知道在创建一个类的时候,是否有必要把__init__
放在第一个方法的位置,就像下面这个例子一样:
class ExampleClass:
def __init__(self, some_message):
self.message = some_message
print "New Class instance created, with message:"
print self.message
另外,为什么我们在调用方法的时候要用self
呢?能不能详细解释一下“self”的用法?
还有,为什么在Python中要使用pass
这个语句呢?
9 个回答
12
你不需要把它放在你的类里面;它是对象的构造函数。
如果你希望在创建对象的时候自动发生一些事情,那你就需要它。
17
除了其他回答之外,你的问题中还有一点没有被提到:
在Python的类中,是否每次都必须把
__init__
放在第一个函数的位置?
答案是否定的。如果你需要一个构造函数,它可以放在代码的任何位置,虽然通常和逻辑上来说,把它放在开头是比较合适的。
131
不,这并不是必须的。
举个例子。
class A(object):
def f():
print 'foo'
当然,你也可以这样使用它:
a = A()
a.f()
实际上,你甚至可以用这种方式定义一个类。
class A:
pass
不过,定义 __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()
类的实例在调用类的方法时总是作为第一个参数传入。例如,如果有 class A
,并且你有一个实例 a = A()
,每当你调用 a.foo(x, y)
时,Python
会自动调用 class A
的 foo(a, x, y)
。(注意第一个参数。)按照惯例,我们把这个第一个参数命名为 self
。