【问题标题】:Call a method from another class for which I cannot inherit从我无法继承的另一个类调用方法
【发布时间】:2021-06-08 13:42:16
【问题描述】:

我想创建一个程序来在购买或出售后更新玩家的银行账户余额。这个播放器是我的解释环境的一部分,因此可以使用get_user() 方法从Environment 类中调用。

当玩家进行购买或销售时,他必须支付可变税款,其金额由Environment 类和get_tax() 方法给出。

如何从 Player 类中调用“get_tax()”方法?

这是我的完整代码及其 cmets

from typing import Any
import random


class BankAccount:
    name: str
    balance: float

    def __init__(self, name: str, balance: float) -> None:
        self.name = name
        self.balance = balance


class Player:
    name: str

    def __init__(self, **kwargs: Any) -> None:
        self.name = kwargs['name']
        self.account_bank = None

    def set_account(self, name, balance) -> None:
        self.account_bank = BankAccount(name, balance)

    def get_account(self) -> BankAccount:
        return self.account_bank

    def buy_something(self, price):
        tax = self.get_tax()                    # How can I get here the amount of the tax from my "Environment" class ?
        self.get_account().balance -= (price * (1 + tax))

    def sell_something(self, price):
        tax = self.get_tax()                    # How can I get here the amount of the tax from my "Environment" class ?
        self.get_account().balance += (price * (1 + tax))

    def action(self, choice, price):
        if choice == 1:
            self.buy_something(price)
        if choice == 2:
            self.sell_something(price)
        else:
            pass


class Environment:

    def __init__(self, tax_min, tax_max):
        self.tax_min = tax_min
        self.tax_max = tax_max

        self.players = {}

    def get_tax(self):
        return random.uniform(self.tax_min, self.tax_max)

    def add_player(self, name: str) -> None:
        kwargs = {'name': name}
        self.players[name] = Player(**kwargs)

    def get_user(self, name: str) -> Player:    # Here I need "-> Player" to be able to call the methods of the "Player" class after calling this method "get_user" and because of which I cannot make an inheritance relation between my Player and Environment classes
        return self.players[name]


env = Environment(0.10, 0.20)                   # Created an environment with a tax varying between 10 and 20%

player_name = 'jason'
env.add_player(player_name)                     # Create player 'jason'

jason = env.get_user(player_name)
jason.set_account('my_account', 100)            # Adds Jason an account with $ 100

jason.action(1, 20)                             # buy something for 20 dollars

print(jason.get_account().__dict__)

【问题讨论】:

  • 是什么阻止您致电env.get_tax()
  • 玩家需要被告知它所处的环境。您可以在创建Player 时给它一个参考。知道税率应该是玩家的工作吗?这听起来应该是商店的责任。
  • 我明白了。我希望税额由环境设置,然后随时被调用......我应该将我的“env”实例作为参数传递给我的“action()”方法,然后传递给我的“buy_something()”和“sell_somthing()”方法,还是在需要j的方法中直接调用“env.get_tax()”更好?
  • “我是否应该将我的“env”实例作为参数传递给我的“action”方法”:如果你要走那条路,并且环境不会改变,我会将env 直接传递给Player,然后您可以在播放器中将env 称为self.env。但是,如果您创建一个商店类,我认为商店处理购买以及商店为玩家计算税款会更有意义。
  • @Carcigenicate 在我的例子中,玩家依赖于在我的代码中由 Environment 类表示的商店。税额随时间而变化。但是如果 2 名玩家想同时购买或出售,他们将不得不支付相同的税

标签: python python-3.x class inheritance


【解决方案1】:

要使用 'Player' 类中的方法,您可以使用 super() 函数。

def get_user(self, name: str) -> Player:    
    return self.players[name]

但你必须先像这样继承'Environment'函数中的'Player'类:

class Environment(Player):

有一个问题。如果你再次在'Environment'类中编写__init__()函数,它会覆盖'Player'类的__init__()函数。为了避免这种情况, 你可以使用 super() 函数。

class Environment(Player):
    def __init__(self, tax_min, tax_max):
        super().__init__(**kwargs) # you don't need 'self' here

记住你必须在 __init__() 函数下编写 super() 函数。
现在,'Player' 类中的方法变成了 'Environment' 类的方法,这样就可以合法使用了。

x = Environment(0.10,0.20)
x.get_account() # a method from 'Player' class

在您的这部分代码中,我建议您将其划分为一个新的类(例如,Action 类)。并使用与以前相同的继承方式从 'Environment' 类中获取税值。

def buy_something(self, price):
    tax = self.get_tax()                   
    self.get_account().balance -= (price * (1 + tax))

def sell_something(self, price):
    tax = self.get_tax()                   
    self.get_account().balance += (price * (1 + tax))

def action(self, choice, price):
    if choice == 1:
        self.buy_something(price)
    if choice == 2:
        self.sell_something(price)
    else:
        pass

有什么不明白的地方吗?

【讨论】:

  • 你的方法很有趣。我尽快测试这个!
  • 我遵循了您的建议,但我无法从 Player 类中调用 get_tax 方法。我收到以下错误:AttributeError: 'Player' object has no attribute 'get_tax'
  • 我是否应该在我的Player 类中调用get_tax 方法,如下所示? self.get_tax()
  • 我认为这是不可能的。与其互相打电话,不如试试这个。将 get_tax() 方法放在主“父类”中。然后继承 'Child' 类中的父方法。接下来创建一个继承“子”类的新类(例如孙子)。这样,'Grandson' 类将继承 'Child' 类和 'Parent' 类的所有方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 2012-04-30
相关资源
最近更新 更多