简体   繁体   English

为类变量python赋值

[英]assigning a value to a class variable python

I have the following class which has two class variables the "value" and the "gradient".I assign two values to the class variables and then print them out.我有以下类,它有两个类变量“值”和“梯度”。我为类变量分配两个值,然后将它们打印出来。 But then I assign 20 to a class variable("limit") that doesn't exist.但是后来我将 20 分配给不存在的类变量(“限制”)。 but the compiler is happy and it seems that stores the variable.但编译器很高兴,似乎存储了变量。 How is this possible?这怎么可能? My assumption was that if the variable name was incorrect I should see an error message.我的假设是,如果变量名称不正确,我应该看到一条错误消息。 shouldn't I ?我不应该吗?

class wire:
    def __init__(self,value,gradient):
        self.value     = value
        self.gradient  = gradient

XX = wire(10,0.05)
print XX.value , XX.gradient

XX.limit = 20
print XX.value , XX.gradient, XX.limit

Thanks for your help谢谢你的帮助

These are instance variables, not class variables.这些是实例变量,而不是类变量。

But I don't know why you expect an error.但我不知道你为什么期望一个错误。 There is no difference between defining those attributes in __init__ or anywhere else.__init__或其他任何地方定义这些属性没有区别。 Either way, you're adding new attributes to the instance.无论哪种方式,您都在向实例添加新属性。

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

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