简体   繁体   English

当一个变量的实例变量在列表中时,如何更改该实例的实例变量

[英]How to change an instance variable of a class when that variable is inside a list

I'm writing a tic-tac-toe game in Python and for one part I have a lot of instance variables in a class and they are all inside a list. 我正在用Python编写井字游戏,有一部分,我在一个类中有很多实例变量,它们都在列表中。 I'm trying to change one the instance variables, but when it is inside the list, I can only change the list element. 我试图更改一个实例变量,但是当它在列表中时,我只能更改列表元素。

Here some code: 这里有一些代码:

# only a piece of my code

class Board(object):
    def __init__(self):
        self.one = "1"
        self.two = "2"
        self.three = "3"

board = Board()

configs = [board.one, board.two, board.three]
configs[2] = "X"
print board.three
print configs

Expected result: 预期结果:

X
['1', '2', 'X']

Actual result: 实际结果:

3
['1', '2', 'X']

Is there the a way to get my expected result? 有没有办法获得我的预期结果?

Strings are immutable objects, so when you change the item in the list with the given index, list now points to totally separate string X . 字符串是不可变的对象,因此当您使用给定索引更改列表中的项目时,列表现在指向完全独立的字符串X

Same scenario applies here; 同样的情况在这里适用;

>>> configs[2] += "X"
>>> print configs[2]
'3X'

>>> print board.three
'3'

One alternative would be to execute a callback function whenever an item in the list gets updated. 一种替代方法是每当列表中的项目被更新时执行回调函数。 (However, I'd personally discourage that, because it seems an hacky solution.) (但是,我个人不建议这样做,因为这似乎是一个棘手的解决方案。)

class interactive_list(list):
    def __init__(self, *args, **kwargs):
        self.callback = kwargs.pop('callback', None)
        super(interactive_list, self).__init__(*args, **kwargs)

    def __setitem__(self, index, value):
        super(interactive_list, self).__setitem__(index, value)
        if self.callback:
            self.callback(index, value)

>>> board = Board()

>>> def my_callback(index, value):
...    if index == 2:
...        board.three = value

>>> configs = interactive_list([board.one, board.two, board.three], callback=my_callback)
>>> configs[2] = 'X'

>>> print board.three
'X'

Have you thought about using better data structures? 您是否考虑过使用更好的数据结构? Like dictionaries ie 像字典一样

class Board(object):
    def __init__(self):
        self.dict = {"one":"1", "two":"2", "three":"3"}

And then you could do something like: 然后您可以执行以下操作:

>>> a = Board()
>>> a.dict
{'three': '3', 'two': '2', 'one': '1'}
>>> for element in a.dict:
    a.dict[element] = element+"x"
>>> a.dict
{'three': 'threex', 'two': 'twox', 'one': 'onex'}
>>> a.dict["one"] = "1"
>>> a.dict
{'three': 'threex', 'two': 'twox', 'one': '1'}

The solution you're looking for is also possible (most likely with some very very weird getattrs etc... and I wouldn't really recommend it. 您正在寻找的解决方案也是可能的(最有可能带有一些非常奇怪的getattrs等...,我真的不推荐使用。

Edit1 It turns out (after checking) that your class attributes will be stored in a object.__dict__ anyhow. Edit1结果(检查后)表明您的类属性将存储在object.__dict__ SO why not use your own. 所以为什么不使用自己的。

Just also to clarify it is possible emulating container objects with your own class by defining __getitem__ and __setitem__ methods like bellow: 还要澄清一下,可以通过定义诸如以下的__getitem____setitem__方法来使用您自己的类来模拟容器对象:

class Board(object):
    def __init__(self):
        self.dict = {"one":"1", "two":"2", "three":"3"}
    def __getitem__(self,key):
        return self.dict[key]
    def __setitem__(self, key, value):
        self.dict[key] = value

Which means you don't have to keep writing a.dict everywhere and can pretend your class is the container (dict) like bellow: 这意味着您不必到处都写a.dict ,并且可以假装您的类是像下面这样的容器(dict):

>>> a = Board()
>>> a.dict
{'three': '3', 'two': '2', 'one': '1'}
>>> a["one"]
'1'
>>> a["one"] = "x"
>>> a.dict
{'three': '3', 'two': '2', 'one': 'x'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 class 中更改另一个相关实例变量时如何更改实例变量? - How to change instance variable when another related instance variable is changed in a class? 如何创建实例变量并在类内部使用? - How to create instance variable and use inside the class? 类型列表的实例变量充当类变量 - Instance variable of type list behaves as class variable 当您将一个类实例附加到另一个类的列表变量时,如何消除重复项? - How to get rid of duplicates when you append a class instance to another class's list variable? 从该类内部的类调用实例变量 - Calling an instance variable from a class that is inside of that class 如何使用类方法获取类列表的实例变量? - How to get instance variable of a class list by using a class method? Class 实例变量在 Python 中弹出不同列表时减少 - Class instance variable is reduced when popping a different list in Python 当类中没有变量时,是否可以初始化实例变量? - Is it possible to initialize a instance variable when there is no variable in the class? 如何将实例变量传递给类定义中的装饰器? - How to pass an instance variable to a decorator inside class definition? 如何一次更改class的所有实例的实例变量,Python - How to change an instance variable of all instances of a class at once, Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM