Aaron
Aaron

Reputation: 1016

Custom Module - Object Has No Attribute

I'm trying to use my own modules but I came across this error and can't seem to figure out how to fix it:

Traceback (most recent call last):
  File "/Users/aaron/Desktop/cg/war.py", line 4, in <module>
AttributeError: Deck instance has no attribute 'test'

From "war.py":

import deck

d = Deck()
test2()
d.test()

From "deck.py":

class Deck:

    def __init__(self):
        self.stack = self.shuffle()
        self.stackSize = len(self.stack)

    def __repr__(self):
        return str(self.stack.items())

    def shuffle(self):
        return {'2c': 'cards/2c.png', '3c': 'cards/3c.png', '4c': 'cards/4c.png', \
                '5c': 'cards/5c.png', '6c': 'cards/6c.png', '7c': 'cards/7c.png', \
                '8c': 'cards/8c.png', '9c': 'cards/9c.png', '10c': 'cards/10c.png', \
                'jc': 'cards/jc.png', 'qc': 'cards/qc.png', 'kc': 'cards/kc.png',
                'ac': 'cards/ac.png'} #continue w/ other suits


    def test():
        print("hello")

def test2():
    print("hello2")

When running "war.py," test2() works and prints "hello". d.test() does NOT work, and gives the error above. How can I fix this?

In the long run, I'm hoping to use the Deck class in other "card game classes" so I don't need to constantly rewrite it. I would like to simply import Deck and use it, so if I'm doing this incorrectly please let me know!

Upvotes: 2

Views: 2954

Answers (1)

PTBNL
PTBNL

Reputation: 6132

The Deck class isn't being found because it isn't in your current name space. To use it, you need to refer to it using the module name. You'll have the same problem with the test2 function. Change war.py to look like this:

import deck

d = deck.Deck()
deck.test2()
d.test()

Another error you will encounter is that your Deck.test method doesn't expect any parameters, but needs to. Add "self" (without quotes) between the parentheses.

Upvotes: 4

Related Questions