我遵循的是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
我错过了什么?你知道吗
在查找属性值时,如果没有名为
foo
的实例属性,则self.foo
将返回到type(self).foo
(粗略地说)。你知道吗当设置一个值时,
self.foo
将始终更新(或者在必要时创建)一个实例属性。必须显式引用类才能修改类属性。你知道吗在您的另一个示例中,
self
“工作”的意义是您验证了uac
的新实例属性inVar
的值。类属性Geek.inVar
保持不变。你知道吗相关问题 更多 >
编程相关推荐