我正在研究faif/python-patterns中的Python模式,但是我不知道何时使用(或传递)没有括号()的类名。
原始代码:
import random
class PetShop(object):
"""A pet shop"""
def __init__(self, animal_factory=None):
"""pet_factory is our abstract factory. We can set it at will."""
self.pet_factory = animal_factory
def show_pet(self):
"""Creates and shows a pet using the abstract factory"""
pet = self.pet_factory()
print("We have a lovely {}".format(pet))
print("It says {}".format(pet.speak()))
class Dog(object):
def speak(self):
return "woof"
def __str__(self):
return "Dog"
class Cat(object):
def speak(self):
return "meow"
def __str__(self):
return "Cat"
# Additional factories:
# Create a random animal
def random_animal():
"""Let's be dynamic!"""
return random.choice([Dog, Cat])()
# Show pets with various factories
if __name__ == "__main__":
# A Shop that sells only cats
cat_shop = PetShop(Cat)
cat_shop.show_pet()
print("")
但是,如果我这样做,它将抛出错误。
if __name__ == "__main__":
# A Shop that sells only cats
cat_shop = PetShop(Cat())
cat_shop.show_pet()
print("")
TypeError: 'Cat' object is not callable
是什么使它仅接受可调用的?而且我知道一个实例是不可调用的,但是一个类名是如何可调用的?
答案 0 :(得分:3)
PetShop
使用一个类(可调用)作为构造函数参数。
Cat()
创建一个Cat
实例,它本身是不可调用的。
因此,您需要将类Cat
传递给PetShop
而不是Cat()
对象:
# A Shop that sells only cats
cat_shop = PetShop(Cat)
cat_shop.show_pet()
print("")