1

I have two classes and wish to append a string to a list in Table() from Game()

Here is my code:

class Table(object):
    def __init__(self):
        self.cards = []

class Game(object):
    def __init__(self):
        Table().cards.append("test")
        print(Table().cards)
0

2 Answers 2

2

In that case, you will need to initialize the class Table inside the class Game like this:

class Table(object):
    def __init__(self):
        self.cards = []

class Game(object):
    def __init__(self):
        table = Table()
        table.cards.append("test")
        print(table.cards)

game = Game()
Sign up to request clarification or add additional context in comments.

6 Comments

I entered this code into pycharm but it still returns nothing when I attempt to print table.cards
Can you share your complete code? Probably the problem is somewhere else. Thanks
I entered this into a completely new test program here is the entire code class Table(object): def __init__(self): self.cards = [] class Game(object): def __init__(self): table = Table() table.cards.append("test") print(table.cards) The output is C:\Users\user\PycharmProjects1\untitled1\poker2\Scripts\python.exe C:/Users/user/Desktop/poker2/test_program.py Process finished with exit code 0
sorry the format is kinda scuffed there I'm new to stack
Did you started the class Game somewhere else in your code?
|
0

Your issue is that in the print statement you are instantiating a brand new instance of Table, and that new instance is empty.

to correct, include the correct instance of Table in the print statement.

class Table(object):
    def __init__(self):
        self.cards = []

class Game(object):
    def __init__(self):
        table = Table()
        table.cards.append('test')
        print(table.cards)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.