ensnare
ensnare

Reputation: 42033

Clear all class variables between instances

This is probably a stupid question, but what's the best way to clear class variables between instances?

I know I could reset each variable individually in the constructor; but is there a way to do this in bulk?

Or am I doing something totally wrong that requires a different approach? Thanks for helping ...

class User():
    def __init__(self):
        #RESET ALL CLASS VARIABLES

    def commit(self):
        #Commit variables to database

>>u = User()
>>u.name = 'Jason'
>>u.email = '[email protected]'
>>u.commit()

So that each time User is called the variables are fresh.

Thanks.

Upvotes: 3

Views: 6263

Answers (4)

Mark Byers
Mark Byers

Reputation: 838276

If you want to reset the values each time you construct a new object then you should be using instance variables, not class variables.

If you use class variables and try to create more than one user object at the same time then one will overwrite the other's changes.

Upvotes: 3

FogleBird
FogleBird

Reputation: 76792

Can you just pass the parameters into the constructor like this?

class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
    def commit(self):
        pass

jason = User('jason', '[email protected]')
jack = User('jack', '[email protected]')

There's nothing to "reset" in the code you posted. Upon constructing a user, they don't even have a name or email attribute until you set them later. An alternative would be to just initialize them to some default values as shown below, but the code I posted above is better so there won't be any uninitialized User objects.

def __init__(self):
    self.user = None
    self.email = None

Upvotes: 3

Mike Graham
Mike Graham

Reputation: 76693

This code does not change the name or email attributes of any of the instances of User except for u.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798696

Binding an attribute on an instance creates instance attributes, not class attributes. Perhaps you are seeing another problem that is not shown in the code above.

Upvotes: 0

Related Questions