我有以下简单示例:
class CatZoo(object):
def __init__(self):
raise NotImplemented
@classmethod
def make_zoo_cat(cls, name, age, gender, location):
cls._names = name
cls._ages = age
cls._genders = gender
cls._location = location
return cls
@classmethod
def make_zoo_cats(cls, names, ages, genders, location):
cls._names = names
cls._ages = ages
cls._genders = genders
cls._location = location
return cls
@property
def location(self):
return self._location
@property
def names(self):
return self._names
def age(self, name):
if name in self._names:
return self._ages[self._names.index(name)]
else:
return None
def gender(self, name):
if name in self._names:
return self._genders[self._names.index(name)]
else:
return None
@property
def meow(self):
return "meow!"
我正在尝试使用以下方法创建此类的对象:
cat_zoo = CatZoo.make_zoo_cat('squeakers', 12, 'M', 'KC')
print "The name is {}".format(cat_zoo.names)
这只是一个示例,我只是想让我的工厂方法起作用(make_zoo_cat、make_zoo_cats)。第一个将传递姓名、年龄、性别和位置,第二个将传递姓名、年龄、性别和一个位置的列表。如果我运行这段代码,我会得到以下输出:
The name is <property object at 0x7fe313b02838>
谢谢,
最佳答案
删除 NotImplemented
初始化器并实际创建类的实例,而不是改变类本身:
class CatZoo(object):
def __init__(self, name, age, gender, location):
self._names = name
self._ages = age
self._genders = gender
self._location = location
@classmethod
def make_zoo_cat(cls, name, ages, genders, location):
return cls.mak_zoo_cats([name], age, gender, location)
@classmethod
def make_zoo_cats(cls, names, ages, genders, location):
return CatZoo(names, age, gender, location)
@property
def location(self):
return self._location
@property
def names(self):
return self._names
def age(self, name):
if name in self._names:
return self._ages[self._names.index(name)]
else:
return None
def gender(self, name):
if name in self._names:
return self._genders[self._names.index(name)]
else:
return None
@property
def meow(self):
return "meow!"
请注意,除了 make_zoo_cat
和 make_zoo_cats
之间的方法名称外,没有真正的区别,参数名称的差异没有改变这里的功能。
相反,我假定 ._names
应该始终是一个列表,并且 make_zoo_cat
(单数)应该创建一个具有一个猫名的 CatZoo
请记住 Python is not Java ;你真的不需要所有那些 property
对象,而不是你可以直接访问属性的地方。
关于python - 创建 python 工厂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22570280/