代码之家  ›  专栏  ›  技术社区  ›  Anonymous

为什么在这个例子中self和类名的用法不同?

  •  0
  • Anonymous  · 技术社区  · 11 月前

    在这段代码中,当我在第四行写类名时,account_id每次都不同,但当我使用self时,account_id的数字将与对象的数量相同,在我学习的参考文献中,它说在这种情况下使用类名和关键字self没有区别,但我在这个例子中看到它不同,原因是什么?我学错了吗?

    class BankAccount():
    
    
    initial_acount_id = 1000110011
        
    def __init__(self, fname, lname, deposit = 0) -> None:
        
        BankAccount.initial_acount_id += 12
        self.account_id = self.initial_acount_id
        self.fname = fname
        self.lname = lname
        self.deposit = deposit
            
    fir = BankAccount("ali", 'zarei')
    sec = BankAccount('mehrdad', 'rsccz', 50)
    thi = BankAccount('sdad', 'ccjkj')
    
    print(fir.account_id)
    print(sec.account_id)
    print(thi.account_id)
    
    1 回复  |  直到 11 月前
        1
  •  2
  •   chepner    11 月前

    我想你是在问 self.initial_account_id += 12 。这不会更新class属性;它创造了一个新的 例子 遮蔽类属性的属性,相当于 self.initial_account_id = self.initial_account_id + 12 对于每个新实例,右侧出现的 self.initial_account_id 尚不存在,因此移交给 BankAccount.initial_account_id .

    假设您没有定义名为的实例属性 initial_account_id 那么 self.account_id = self.initial_account_id 将按预期工作(RHS决定 银行账户.initial_account_id ),但最好还是明确一点:

    class BankAccount:
    
    
        initial_account_id = 1000110011
            
        def __init__(self, fname, lname, deposit = 0) -> None:
            
            BankAccount.initial_account_id += 12
            self.account_id = BankAccount.initial_account_id
            self.fname = fname
            self.lname = lname
            self.deposit = deposit
    

    (也就是说,如果你 打算 要使用类属性,请这样说,而不是通过类的实例隐式访问它。)

    更好的是,从中删除递增帐户ID的(显式)逻辑 BankAccount.__init__ ,并通过使用迭代器隐式地执行此操作。

    from itertools import count
    
    
    class BankAccount:
        initial_account_id = count(1000110011, 12)
            
        def __init__(self, fname, lname, deposit = 0) -> None:
            # As an aside, self.initial_account_id here would
            # be safe, since we aren't *assigning* to the attribute, only calling
            # one of its mutating methods.
            self.account_id = next(BankAccount.initial_account_id)
            self.fname = fname
            self.lname = lname
            self.deposit = deposit