gpt4 book ai didi

python - 每次在 Python 中的类中是否有必要将 __init__ 作为第一个函数?

转载 作者:IT老高 更新时间:2023-10-28 21:53:02 25 4
gpt4 key购买 nike

在 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 语句?

最佳答案

不,没必要。

例如。

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 Afoo(a, x, y)。 (注意第一个参数。)按照惯例,我们将第一个参数命名为 self

关于python - 每次在 Python 中的类中是否有必要将 __init__ 作为第一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6854080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com