我遵循这个 Python 设计模式,关于 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.__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
我错过了什么?
查找属性的值时,如果没有名为foo
的实例属性,self.foo
将回退到type(self).foo
(粗略地说)。
但是,在设置值时,self.foo
将始终更新(或在必要时创建)实例属性。您必须显式引用类才能修改类属性。
在您的另一个示例中,self
"有效",因为您验证了新实例属性的值inVar
uac
。类属性Geek.inVar
保持不变。