Python class attributes - reset

What is the best way to reset class attributes in Python.

I have a class that has about 20 class attributes, in my init I have

class MyClass:
    def __init__(self)
       self.time=0
       self.pos=0
       self.vel=0
       self.acc=0
       self.rot=0
       self.dyn=0

This should be reset at every iteration of my program, which is the easiest way to do this, and not set to zero, as shown above.

thank

+3
source share
4 answers

I would prefer not to reset them in the method init, but to define a method for this resetand call resetfrom initand before each subsequent iteration.

+4
source

you can use vars () to return a dictionary of values ​​that you can edit.

something like that

class A:
    def __init__(self):
        self.a=1
        self.b=1

    def reset(self):
        dic = vars(self)
        for i in dic.keys():
            dic[i] = 0

inst = A()
print inst.a , inst.b  # will print 1 1
inst.reset()
print inst.a , inst.b  # will print 0 0

, -

def reset(self):
    dic = vars(self)
    noEdit = ['a']
    for i in dic.keys():
        if i not in noEdit:
            dic[i] = 0

a, , , oop .

+4
class MyClass(object):
  def __init__(self):
    attribs = 'time', 'pos', 'vel', 'acc', 'rot', 'dyn'
    vars(self).update((x, 0) for x in attribs)
+2
source

I'm not sure if this is more neat, but:

class MyClass:
    def __init__(self):
        for v in ('time', 'pos', 'vel', 'acc', 'rot', 'dyn'):
            exec("self.%s = 0" % v)

As SilentGhost suggested, you should probably put them in a reasonable data structure, such as a tuple, for example.

class MyClass:
    def __init__(self):
        self.values = 20*(0,)

or, you can use the dictionary:

class MyClass:
    def __init__(self):
        self.data = {}
        for v in ('time', 'pos', 'vel', 'acc', 'rot', 'dyn'):
        self.data[v] = 0
0
source

Source: https://habr.com/ru/post/1729538/


All Articles