有没有办法通过装饰器访问类属性?

时间:2020-07-09 06:00:59

标签: python class oop decorator python-decorators

我正在与装饰员一起在一个简单的银行帐户类上练习。我正在尝试通过装饰器显示“ self.balance”。但是,由于范围的原因,我遇到了“ NameError”。有什么办法解决吗?

def statement(f):
    def helper(*args):
        f(*args)
        print(f"{f.__name__} of {args[1]} completed. \nYour new balance is {self.balance}")
    return helper

class Account:
    def __init__(self):
        with open('balance.txt', 'r') as file:
            self.balance = float(file.read())

    @statement
    def deposit(self, amount):
        self.balance += amount

    @statement
    def withdrawal(self, amount):
        self.balance -= amount

0 个答案:

没有答案