Python Recursion within Class

前端 未结 2 1555
闹比i
闹比i 2021-02-02 17:49

I just learn python today, and so am thinking about writing a code about recursion, naively. So how can we achieve the following in python?

class mine:
    def          


        
相关标签:
2条回答
  • Each method of a class has to have self as a first parameter, i.e. do this:

    def recur(self, num):
    

    and it should work now.

    Basically what happens behind the scene is when you do

    instance.method(arg1, arg2, arg3, ...)
    

    Python does

    Class.method(instance, arg1, arg2, arg3, ....)
    
    0 讨论(0)
  • 2021-02-02 18:16

    This is a code example that actually works

    class Card():
        def __init__(self,cardsPlayedList,cardPosition):
            self.cardsPlayedList = cardsPlayedList
            self.cardPosition = cardPosition
        #    self.cardPosition
    
        def getNewCard(self,cardPosition):
            cardNum = 0
            cardInList = False
            
            cardNum = random.randint(1,len(cardList)-1)          # Get random card from List - 1 to 52 
            for x in self.cardsPlayedList:
                if(cardNum == x):
                    cardInList = True                            
    
            if(cardInList == False):
                self.cardsPlayedList.insert(self.cardPosition, cardNum)    # if card not already played then store in list
                return cardNum
            else:
                return self.getNewCard(cardPosition)   
    
    0 讨论(0)
提交回复
热议问题