Python-对可调用和构造函数感到困惑

时间:2018-08-28 04:36:26

标签: python

我正在研究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

是什么使它仅接受可调用的?而且我知道一个实例是不可调用的,但是一个类名是如何可调用的?

1 个答案:

答案 0 :(得分:3)

PetShop使用一个类(可调用)作为构造函数参数。

Cat()创建一个Cat实例,它本身是不可调用的。

因此,您需要将类Cat传递给PetShop而不是Cat()对象:

# A Shop that sells only cats
cat_shop = PetShop(Cat)
cat_shop.show_pet()
print("")