0

您好,我的任务很简单,但我又被卡住了:

如何将类中的变量用于描述符?

我有commission来自父类的变量,我需要在调用时将它用于描述符setself.amount = int(amount) * int(commission)

我怎样才能做到这一点?

谢谢!

完整代码如下:

class Value():
    def __init__(self):

        return

    def __get__(self, obj, obj_type):
        return self.amount

    def __set__(self, obj, amount, commission):
        self.amount = int(amount) * int(commission)


class Account:

    def __init__(self, commission):
        self.commission = commission

    amount = Value(self.commission)

new_account = Account(0.1)
new_account.amount = 100

print(new_account.amount)
4

1 回答 1

0

正确的代码如下:

class Value():
    def __init__(self):
        return

    def __get__(self, obj, obj_type):
        return self.value

    def __set__(self, obj, value):
        self.value = value * (1 - obj.commission)


class Account:
    amount = Value()

    def __init__(self, commission):
        self.commission = commission


new_account = Account(0.1)
new_account.amount = 100

print(new_account.amount)

诀窍是,当您调用__set__描述符时,您将 obj 传递到内部,并且您可以像往常一样调用任何变量或方法 obj.xxx,这是我知道的基本知识,但我真的是 OOP 的菜鸟。

于 2018-03-11T13:34:16.193 回答