Python OOP - 无法使用s更改类变量的值

2024-05-09 01:54:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我遵循的是thisPython设计模式,关于initialization()函数有一些我不明白的地方:

class ObjectFactory:

   """ Manages prototypes.
   Static factory, that encapsulates prototype
   initialization and then allows instatiation
   of the classes from these prototypes.
   """

   __type1Value1 = None
   __type1Value2 = None
   __type2Value1 = None
   __type2Value2 = None

   @staticmethod
   def initialize():
      ObjectFactory.__type1Value1 = Type1(1)
      ObjectFactory.__type1Value2 = Type1(2)
      ObjectFactory.__type2Value1 = Type2(1)
      ObjectFactory.__type2Value2 = Type2(2)

为什么变量的init使用类的名称(即ObjectFactory.__type1Value1)而不使用self(即self.__type1Value1)? 当我变成自我时:

   def initialize(self):
      self.__type1Value1 = Type1(1)
      self.__type1Value2 = Type1(2)
      self.__type2Value1 = Type2(1)
      self.__type2Value2 = Type2(2)

我有个错误TypeError: initialize() missing 1 required positional argument: 'self'。你知道吗

但在另一个例子中,使用“self”是有效的:

class Geek: 

    # Variable defined inside the class. 
    inVar = 'inside_class'
    print("Inside_class2", inVar) 

    def access_method(self): 
        self.inVar="a"
        print("Inside_class3", self.inVar) 

uac = Geek() 
uac.access_method()

输出:

Inside_class2 inside_class
Inside_class3 a

我错过了什么?你知道吗


Tags: selfnonedefclassinsideinitializetype1type2
1条回答
网友
1楼 · 发布于 2024-05-09 01:54:40

在查找属性值时,如果没有名为foo的实例属性,则self.foo将返回到type(self).foo(粗略地说)。你知道吗

设置一个值时,self.foo始终更新(或者在必要时创建)一个实例属性。必须显式引用类才能修改类属性。你知道吗

在您的另一个示例中,self“工作”的意义是您验证了uac的新实例属性inVar的值。类属性Geek.inVar保持不变。你知道吗

相关问题 更多 >

    热门问题