首页 > 解决方案 > Appending strings across classes in python

问题描述

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)

标签: pythonpython-3.xlist

解决方案


在这种情况下,您需要像这样在Game类中初始化Table类:

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()

推荐阅读