繁体   English   中英

Python 3 如何在类中使用循环

[英]Python 3 how to use loops with classes

我正在锦标赛中创建卖家/买家模拟,以查看卖家是接受还是拒绝买家的报价。

我已经为卖家和买家制定了几种策略,写成类。 每个买家 class 都有一个返回特定报价的报价方法,而卖家 class 有一个接受买家报价的审查方法,如果它处于他们接受的“阈值”,它就会被移到一个空数组中。 阵列越满,发生的“接受”就越多。

我还添加了 id 属性,以便能够关注更多谁在比赛中玩谁

卖家示例class:

    def __init__(self):
        self.offer_history = []
       
    def review(self, offer):
        self.offer_history.append(offer)
        return offer > twoThirdsOfPrice
    
    def idcode(self):
        self.idcode = 11 

买家示例 class

class offerLow():        
    def offer(self):
        return (thirdOfPrice * random.random())
    
    def idcode(self):
        self.idcode = 21

我正在尝试创建一个循环使用这些不同策略的锦标赛,以便每个卖家都玩每个报价者。 这是到目前为止的比赛。 我一直收到类似的错误

offer() missing 1 required positional argument: 'self'

并认为我误解了如何让这个循环工作。

offerer_strategies = [offerLow, offerMed, offerHigh, randomLowerHalf, alwaysHalf, lowButReasonable, luckTester, 
                      takeTheAverage]

seller_strategies = [acceptLow, acceptMed, acceptHigh, averageHuman]

outcomes = []

n=0

for offerer in offer_strategies:
    for seller in seller_strategies:
        n+=1
        offerer = offerer_strategies[n]
        seller = seller_strategies[n]
        score = sum(seller.review(offerer.offer()) for _ in range(500))
        outcomes.append(concat(seller.idcode, offerer.idcode), score)

您的 class offerLow有两个实例方法offeridcode但没有__init__方法来初始化实例。 您可以添加@staticmethod装饰器以使您的代码正常工作。 像这样:

class offerLow():
    @staticmethod
    def offer(self):
        return (thirdOfPrice * random.random())
    
    @staticmethod
    def idcode(self):
        self.idcode = 21

有关实例方法、class 方法和 static 方法的更多信息: https://realpython.com/instance-class-and-static-methods-demystified/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM