'Newbie Class Inheritance Question (python)
class Deck(Cards):
def __init__(self):
self.mycardset = []
for num in self.values:
for shp in self.suites:
self.mycardset.append(num+' of '+ shp)
def shuffleDeck(self):
self.mycardset = shuffle(self.mycardset)
def main():
deck = Deck()
print(f'[Current Deck]\n{deck.mycardset}')
shuffled_deck = deck.shuffleDeck()
print(f'[Shuffled Deck]\n{shuffled_deck.mycardset}')
AttributeError: 'NoneType' object has no attribute 'mycardset'
I don't think it's saved on the list, how can I fix it?
Solution 1:[1]
suffleDeck method doesn't return anything (or returns a None), modifying your class in place, so you are assigning shuffled_deck as None, hence your error. Just call your method on the deck variable and access the mycardset attribute from it instead
def main():
deck = Deck()
print(f'[Current Deck]\n{deck.mycardset}')
# Suffle deck in place
deck.shuffleDeck()
print(f'[Shuffled Deck]\n{deck.mycardset}')
Other option would be to modify shuffleDeck() to return self
def shuffleDeck(self):
self.mycardset = shuffle(self.mycardset)
return self
but keep in mind, this still modifies deck as well, since now both variables point to the same object in memory. If you want to create a new deck and shuffle, while maintaining the original object, simplest way would be to copy the original deck before shuffling
import copy
def shuffleDeck(self):
new = copy.deepcopy(self)
new.mycardset = shuffle(self.mycardset)
return new
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
