开发者

Clear all class variables between instances

开发者 https://www.devze.com 2022-12-24 09:35 出处:网络
This is probably a stupid question, but what\'s the best way to clear 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.e开发者_如何学Cmail = 'jason.mendez@yahoo.com.mx'
>>u.commit()

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

Thanks.


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', 'jason@email.com')
jack = User('jack', 'jack@yahoo.com')

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


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号