I'm trying to pass a class object as an argument to a global function.
Here's the function:
def CreatePlayers(p1_Name, p2_Name, cardDeck):
#Function to Create Players
#Takes 3 variables: Names of player 1 and player 2 and the card deck
#Returns a List of players [p1,p2]
print("Creating Players... \n")
print(f"Dealing a deck of ", len(cardDeck), " among 2 players")
player1 = Player(p1_Name)
player2 = Player(p2_Name)
#Share cards between players
for i in range(25):
player1.addCard(cardDeck.dealOne())
player2.addCard(cardDeck.dealOne())
print("Verify... player creation\n")
print(player1)
print(player2)
return [player1, player2]
The class object here's "cardDeck", and the class object is initialized before making the function call with the variable name, of course
And here's the class definition:
class Deck:
'''A Python Deck class. Holds a list of Card objects
Possesses the following
* Attributes: - myDeck (A list of cards. Expected = 50 cards in deck)
* Methods: - Constructor (creates list)
- Shuffle
- Deal a card
- return number of cards
'''
def __init__(self):
'''Method to initialize a deck'''
self.myDeck = []
#initialize cards
for rank in Ranks:
for order in Orders:
self.myDeck.append( Card(order, rank) )
##other functions....
def __len__(self):
'''Return the size of the card deck'''
return len(self.myDeck)
This is where I call my createPlayer() function:
myDeck = Deck().shuffle()
#Create my players
players = CreatePlayers("Adam", "Bob", myDeck)
And finally here's the error that I keep getting while running the 'createPlayer' function
File "/home/CardGame.py", line 32, in CreatePlayers print(f"Dealing a deck of ", len(cardDeck), " among 2 players") TypeError: object of type 'NoneType' has no len()
CodePudding user response:
Deck().shuffle()
doesn't return the deck
you can do this to solve it :
myDeck = Deck();
myDeck.shuffle();
players = CreatePlayers("Adam", "Bob", myDeck)
an other alternative is to change shuffle to be a class method :
class Deck:
def __init__(self):
...
@classmethod
def shuffle(cls):
new_deck = cls()
# Do shuffle here for new_deck
return new_deck
and use it that way :
myDeck = Deck.shuffle();
players = CreatePlayers("Adam", "Bob", myDeck)
but that way you can't shuffle an existing deck so it depend on what you want to do.