简体   繁体   中英

Calling a Python method from one class to another

class A: 
    def getTotal(self)
        self.__total = 0
        for each in self.__hand:
            if each.getValue() == 1 and self.__total > 10:
                self.__total += 1
            elif each.getValue() == 1 and self.__total <10:
                self.__total += 11
            elif each.getValue() != 1:
                self.__total += each.getValue()
        return self.__total

class B: 
    def getTotal(self):
        return A.getTotal()

This isn't working for me. How can I get class A to return a total when called from class B's method

You cannot just call A.getTotal() because it is an unbound method ; there is nothing to bind self to as you didn't give it an instance of A , where you'd have state. You need to call it on an instance of A . We just need to find one first.

From the comments I understand B to the the player, and A is a hand of cards for that player. Presumably in a game a player can play end up with more hands as multiple rounds are played.

In that case you'd have a reference from the player to the hand, like self.hand . That'd be an instance of A and you can call getTotal() on that instead:

class B:
    def getTotal(self):
        return self.hand.getTotal()

It may be confusing here that A also has a __hand attribute; that's perhaps not the best name for that attribute, as it is the list of cards for the current hand. It could perhaps better be named __cards in that case.

B.getTotal() is not strictly needed; you could also just use instance_of_B.hand.getTotal() , eg reach right into the instance attributes and call getTotal() directly on the hand. But that'd perhaps reveal too much about how the class handles hands, and perhaps you want to handle different cases, like return 0 if there is the possibility that at some points in the program is no hand at all.

And another thing: __total in A.getTotal() is a local variable; you don't need to use an attribute on self there. Remove the self. prefix, and just name it total :

def getTotal(self)
    total = 0
    for each in self.__hand:
        if each.getValue() == 1:
            if total > 10:
                total += 1
            else:
                total += 11
        else:
            total += each.getValue()
    return total

I simplified the function logic a little too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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