"Pythonic" “重置"方式对象的变量? [英] "Pythonic" way to "reset" an object's variables?

查看:79
本文介绍了"Pythonic" “重置"方式对象的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(变量"在这里是指名称",我认为并不是完全确定pythonistas使用的定义)

我有一个对象和一些方法.这些方法都需要并且都更改了对象的变量.我如何在最Python最好的情况下,尊重OOP的技术,既可以使方法使用对象变量,又可以保留其他方法的原始值?

I have an object and some methods. These methods all need and all change the object's variables. How can I, in the most pythonic and in the best, respecting the techniques of OOP, way achieve to have the object variables used by the methods but also keep their original values for the other methods?

我应该在每次调用方法时复制对象吗?我是否应该保存原始值并使用reset()方法在每次方法需要它们时将其重置?还是有更好的方法?

Should I copy the object everytime a method is called? Should I save the original values and have a reset() method to reset them everytime a method needs them? Or is there an even better way?

编辑:有人要求我输入伪代码.因为我对理解概念感兴趣,而不是仅仅专门解决遇到的问题,所以我将尝试举一个例子:

I was asked for pseudocode. Since I am more interested in understanding the concept rather than just specifically solving the problem I am encountering I am going to try give an example:

class Player():
    games = 0
    points = 0
    fouls = 0
    rebounds = 0
    assists = 0
    turnovers = 0
    steals = 0

    def playCupGame(self):
        # simulates a game and then assigns values to the variables, accordingly
        self.points = K #just an example

    def playLeagueGame(self):
        # simulates a game and then assigns values to the variables, accordingly
        self.points = Z #just an example
        self.rebounds = W #example again

    def playTrainingGame(self):
        # simulates a game and then assigns values to the variables, accordingly
        self.points = X #just an example
        self.rebounds = Y #example again

上面是我的Player对象类(例如,假设他是篮球运动员).该对象具有三种不同的方法,全部为玩家的统计信息分配值.

The above is my class for a Player object (for the example assume he is a basketball one). This object has three different methods that all assign values to the players' statistics.

所以,假设球队有两场联赛比赛,然后是一场杯赛.我必须打这些电话:

So, let's say the team has two league games and then a cup game. I'd have to make these calls:

p.playLeagueGame()
p.playLeagueGame()
p.playCupGame()

很明显,在拨打第二个和第三个电话时,需要重置之前更改的播放器统计信息.为此,我可以编写一个将所有变量都设置为0的reset方法,也可以为我进行的每次调用复制对象.或者做一些完全不同的事情.

It's obvious that when the second and the third calls are made, the previously changed statistics of the player need to be reset. For that, I can either write a reset method that sets all the variables back to 0, or copy the object for every call I make. Or do something completely different.

这就是我的问题所在,python和oop明智的最佳方法是什么?

That's where my question lays, what's the best approach, python and oop wise?

更新:我怀疑我对此过于复杂了,并且可以通过在函数中使用局部变量来轻松解决我的问题.但是,如果我在另一个函数中有一个函数,会发生什么情况,我可以在内部函数中使用外部函数的局部变量吗?

UPDATE: I am suspicious that I have superovercomplicated this and I can easily solve my problem by using local variables in the functions. However, what happens if I have a function inside another function, can I use locals of the outer one inside the inner one?

推荐答案

不确定它是否足够"Pythonic",但是您可以定义可重置的"修饰符 为__init__方法创建一个对象的__dict__副本,并添加一个reset()方法,该方法将当前__dict__切换为原始对象.

Not sure if it's "Pythonic" enough, but you can define a "resettable" decorator for the __init__ method that creates a copy the object's __dict__ and adds a reset() method that switches the current __dict__ to the original one.

编辑-这是一个示例实现:

Edit - Here's an example implementation:

def resettable(f):
    import copy

    def __init_and_copy__(self, *args, **kwargs):
        f(self, *args)
        self.__original_dict__ = copy.deepcopy(self.__dict__)

        def reset(o = self):
            o.__dict__ = o.__original_dict__

        self.reset = reset

    return __init_and_copy__

class Point(object):
    @resettable
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return "%d %d" % (self.x, self.y)

class LabeledPoint(Point):
    @resettable
    def __init__(self, x, y, label):
        self.x = x
        self.y = y
        self.label = label

    def __str__(self):
        return "%d %d (%s)" % (self.x, self.y, self.label)

p = Point(1, 2)

print p # 1 2

p.x = 15
p.y = 25

print p # 15 25

p.reset()

print p # 1 2

p2 = LabeledPoint(1, 2, "Test")

print p2 # 1 2 (Test)

p2.x = 3
p2.label = "Test2"

print p2 # 3 2 (Test2)

p2.reset()

print p2 # 1 2 (Test)

Edit2:添加了具有继承性的测试

Added a test with inheritance

这篇关于"Pythonic" “重置"方式对象的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆