在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.
除了其他答案之外,您问题中的一点尚未解决:
是否有必要在Python中的每个类中包含
__init__第一个函数?
答案是不.在您需要构造函数的情况下,它可以位于代码的任何位置,尽管传统和逻辑位置是开始.
| 归档时间: |
|
| 查看次数: |
36816 次 |
| 最近记录: |