为什么类变量从方法和外部读取是不同的?

Ego*_*rov 2 python oop

所以,我创建了一些课程

class Some:
    @classmethod
    def __init__(cls, somevar):
        cls.somevar = somevar

    @classmethod
    def read(cls):
        return cls.somevar
Run Code Online (Sandbox Code Playgroud)

现在我尝试在外部设置变量并从类中读取它:

instance = Some([1, 2, 3])
instance.somevar = [4, 5, 6]
print(instance.read())

>>>> [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

但是在类外调用相同的命名变量会给我预期的输出,

print(instance.somevar)
>>>> [4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

我对OOP的误解是什么?

编辑

我的目标是创建Some具有自己值的多个实例.

sch*_*tte 5

实际上,你误解了类变量是什么.当你使用时

instance.somevar = [4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

它不会改变你认为的价值.相反,你需要做的是改变实际的类变量,如下所示,

instance = Some([1, 2, 3])
instance.somevar = [4, 5, 6]
print(instance.read())
instance2 = Some([4, 5, 6])
print(instance.read())

>>>>
[1, 2, 3]
[4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

确实,不要忘记通过使用@classmethod装饰器,cls实际上是类本身.因此,在您的情况下,cls.somevar将在所有类中共享.此外,由于您对自己进行了修饰__init__,因此每次实例化该类时,您都将更改该变量的值,如上例所示.


请注意,这可能不是您正在寻找的实现.你可能想要这样使用self,

class Some:
    def __init__(self, somevar):
        self.somevar = somevar

    def read(self):
        return self.somevar

instance = Some([1, 2, 3])
print(instance.read())
instance.somevar = [4, 5, 6]
print(instance.read())

>>>>
[1, 2, 3]
[4, 5, 6]
Run Code Online (Sandbox Code Playgroud)