简体   繁体   English

清除实例之间的所有类变量

[英]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 = 'jason.mendez@yahoo.com.mx'
>>u.commit()

So that each time User is called the variables are fresh. 这样每次调用User时变量都是新鲜的。

Thanks. 谢谢。

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. 如果您使用类变量并尝试同时创建多个用户对象,则会覆盖其他用户对象。

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. 另一种方法是将它们初始化为一些默认值,如下所示,但我上面发布的代码更好,因此不会有任何未初始化的User对象。

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

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. 也许您正在看到上面代码中未显示的另一个问题。

除了u之外,此代码不会更改User的任何实例的nameemail属性。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM