-4

I am expecting obj1 and obj2 will have different deck.cards, why they are the same, how do I make them 2 instance?

class deck:
    cards ={}
    def __init__(self, key, value):
        self.cards[key]=value
        return
>>> obj1 = deck("a", "1")
>>> obj2 = deck("b", "2")
>>> print (obj1.cards, obj2.cards)
{'a': '1', 'b': '2'} {'a': '1', 'b': '2'}
  • 4
    Issue is [Class vs Instance Variable](https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3) You have cards as a class variable so it will be the same for all instances. – DarrylG Jan 19 '20 at 02:50

1 Answers1

0

In your code, the value for cards in both instances is the same because you have made cards a class variable, which means that it is shared by all instances of the class.

To fix your problem, make cards an instance variable. Write your class like this:

class Deck:
    def __init__(self, key, value):
        self.cards = {
            key: value,
        }

Note that return is unnecessary, as the initializer is going to return at the end anyway.

Flux
  • 9,805
  • 5
  • 46
  • 92
  • ```>>> class Deck: def __init__(self, key, value): self.cards = { key: value, } >>> a=deck("a", "b") Traceback (most recent call last): File "", line 1, in a=deck("a", "b") File "", line 3, in __init__ self.cards[key]=value AttributeError: 'deck' object has no attribute 'cards' >>> ``` – Silicon Creature Jan 19 '20 at 05:40
  • @SiliconCreature You should use the `Deck` you have defined (and not `deck`). Notice the capital letter. – Flux Jan 19 '20 at 07:33