Skip to main content
 首页 » 编程设计

python之__init__.storing 是什么信息

2025年05月04日11jillzhang

我在某处读到 __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  
 
myAccount = BankAccount(16.20) 
 
x = raw_input("What would you like to do?") 
 
if x == "deposit":     
    myAccount.deposit(int(float(raw_input("How much would you like to deposit?")))) 
    print "Total balance is: ", myAccount.balance()    
elif x == "withdraw":     
    myAccount.withdraw(int(float(raw_input("How much would you like to withdraw?")))) 
    print "Total balance is: ", myAccount.balance()     
else: 
    print "Please choose 'withdraw' or 'deposit'. Thank you." 

__init__ 正在做什么或存储什么。我不明白“self.amount”是什么,也不知道 make it = deposit 是如何做的。 __init__下的“self.amount”和withdraw下的是一样的吗?我只是不明白“self_amount”的作用。

请您参考如下方法:

问 __init__ 正在做什么或存储什么?

A __init__ 会在您构造该类的实例时被调用。这适用于所有类别。通常在此函数中初始化所有数据。在您的特定情况下,您正在创建一个名为 amount 的成员数据,并将其分配为与传递给该函数的 deposit 参数相同。

问 我不明白"self.amount" 是什么,也不明白= deposit 是如何做的。

A self.amount = deposit 语句完成了几件事。它创建了一个名为 amount 的类的成员数据,并将其分配给 deposit 的值。

Q__init__下的"self.amount"和withdraw下的是一样的吗?

一个是的。

问 我只是不明白"self.amount" 的作用。

A 它允许您捕获对象的数据。每个类都需要找出正确工作所需的成员数据。在您的情况下,您唯一需要的数据是数量。如果您有一个名为 Employee 的类,它可能类似于:

class Employee(object): 
    def __init__(self, firstName, lastName, id, salary): 
        self.firstName = firstName  
        self.lastName = lastName  
        self.id = id  
        self.salary = salary