【问题标题】:Referencing other objects of same class in a method of a class in Python在Python中的类的方法中引用同一类的其他对象
【发布时间】:2021-04-12 17:19:55
【问题描述】:

我是编程和学习 Python 的新手。现在我正试图弄清楚如何在类内的方法定义中将值写入同一类的另一个对象。我的意思是这样的:

class myClass:
    def __init__(self, attribute, lst = True):
    self.attribute = attribute
    if lst is True:
        self.lst = []

    def add_amount(self, amount):
        self.lst.append(dict(Amount = amount))

    def total:
        self.total = []
        for each in self.lst:
            self.total.append(each.get("Amount"))
        self.total = sum(self.total)

    #def transfer(self, amount, attribute):
        #here I would like to be able to add
        #a value (for example self.total) to
        #the lst [] of a different instance of
        #this class

firstInstance = myClass("First")
secondInstance = myClass("Second")

firstInstance.add_amount(10)
firstInstance.add_amount(20)
  
##firstInstance.transfer(15, "Second")

#How can I write the transfer
#function so that it will add
#the value of the first argument 
#to the empty list of the instance
#object with the attribute "Second" 
#(in this case secondInstance)?

我该如何编程?我希望我能以一种可以理解的方式解释我的问题,希望你们能帮助我!提前致谢! :)

亲切的问候

【问题讨论】:

    标签: python class object methods


    【解决方案1】:

    您必须将 secondInstance 作为参数传递给您的 transfer 函数。你可能会做这样的事情:

    class myClass:
        def __init__(self, attribute, lst = True):
        self.attribute = attribute
        if lst is True:
            self.lst = []
    
        def add_amount(self, amount):
            self.lst.append(dict(Amount = amount))
    
        def subract_amount(self, amount):
            # TODO
            pass
    
        def total:
            self.total = []
            for each in self.lst:
                self.total.append(each.get("Amount"))
            self.total = sum(self.total)
    
        def transfer(self, amount, other):
            self.subtract_amount(amount)
            other.add_amount(amount)
    
    
    firstInstance = myClass("First")
    secondInstance = myClass("Second")
    
    firstInstance.add_amount(10)
    firstInstance.add_amount(20)
      
    firstInstance.transfer(15, secondInstance)
    

    【讨论】:

    • 非常感谢您的快速回复,很抱歉这么晚才回复!您建议的方式有效,但我试图输入实际的属性名称(即,如果我想从“服装”转移到“工具”,我想将“工具”的属性名称作为参数放入方法中)我想在方法中作为参数传输的对象,而不是对象名称本身。如果你不能那样做,我会相应地命名对象。有没有办法像我以前想象的那样做?再次感谢,非常感谢你们花时间回答问题!
    • 您建议的方式是可能的。我建议研究中介者设计模式来实现你想要的。这是一个示例:refactoring.guru/design-patterns/mediator/python/example 考虑简单地构建一个处理所有 myClass 实例的 myClassMediator 类。 myClassMediator 管理器将能够在内部跟踪每个实例。
    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2015-03-13
    相关资源
    最近更新 更多