什么'班级括号的含义?

时间:2014-12-02 01:11:02

标签: python

在python中,当我阅读其他人的代码时,我遇到了定义类的情况,之后有一对括号。

class AStarFoodSearchAgent(SearchAgent):
     def __init__():
        #....

我不知道'(SearchAgent)'的含义是什么,因为我通常遇到和使用的东西似乎并不是这样。

5 个答案:

答案 0 :(得分:1)

它表示AStarFoodSearchAgentSearchAgent子类。它是继承概念的一部分。

什么是继承?

这是一个例子。您可能有一个Car类和一个RaceCar类。在实现RaceCar类时,您可能会发现它有很多与Car非常相似或完全相同的行为。在这种情况下,你可以制作RaceCar a subclass of Car。。

class Car(object):
    #Car is a subclass of Python's base objeect. The reasons for this, and the reasons why you 
    #see some classes without (object) or any other class between brackets is beyond the scope 
    #of this answer.

    def get_number_of_wheels(self):
        return 4

    def get_engine(self):
        return CarEngine(fuel=30)

class RaceCar(Car):
#Racecar is a subclass of Car
    def get_engine(self):
        return RaceCarEngine(fuel=50)

my_car = Car() #create a new Car instance
desired_car = RaceCar() #create a new RaceCar instance.
my_car.get_engine() #returns a CarEngine instance
desired_car.get_engine() #returns a RaceCarEngine instance

my_car.get_number_of_wheels() #returns 4.
desired_car.get_number_of_wheels() # also returns 4! WHAT?!?!?!

我们没有在get_number_of_wheels上定义RaceCar,但仍然存在,并在调用时返回4。那是因为RaceCarget_number_of_wheels继承了Car。继承是重用其他类功能的一种非常好的方法,并且只覆盖或添加需要不同的功能。

您的示例

在您的示例中,AStarFoodSearchAgentSearchAgent的子类。这意味着它继承了SearchAgemt的一些功能。例如,SearchAgent可能会实现一个名为get_neighbouring_locations()的方法,该方法返回从代理的当前位置可到达的所有位置。没有必要重新实现这一点,只是为了建立一个A *代理。

对此有什么好处,是你可以在期望某种类型的对象时使用它,但是你不关心实现。例如,find_food函数可能需要SearchAgent个对象,但它不会关心它的搜索方式。您可能拥有AStarFoodSearchAgentDijkstraFoodSearchAgent。只要这两个都继承自SearchAgentfind_food就可以使用“实例to check that the searcher it expects behaves like a SearchAgent . The find_food`功能可能如下所示:

def find_food(searcher):
    if not isinstance(searcher, SearchAgent):
        raise ValueError("searcher must be a SearchAgent instance.")

    food = searcher.find_food()
    if not food:
        raise Exception("No, food. We'll starve!")
    if food.type == "sprouts":
        raise Exception("Sprouts, Yuk!)
    return food

旧/经典样式类

Upto Python 2.1,旧式类是唯一存在的类型。除非它们是某个其他类的子类,否则它们在类名后不会有任何括号。

class OldStyleCar:
    ...

新样式类总是从某些东西继承而来。如果您不想从任何其他类继承,则继承自object

class NewStyleCar(object):
    ...

新样式类统一了python类型和类。例如,您可以通过调用1获得的type(1)类型为int,但OldStyleClass()的类型为instance,具有新的样式类,type(NewStyleCar)Car

答案 1 :(得分:0)

SearchAgent是类AStarFoodSearchAgent的超类。这基本上意味着AStarFoodSearchAgent是一种特殊的SearchAgent

答案 2 :(得分:0)

这意味着 AStarFoodSearchAgent 类扩展 SearchAgent

检查第9.5节

https://docs.python.org/2/tutorial/classes.html

答案 3 :(得分:0)

这是python中的继承,就像任何其他OO语言一样

https://docs.python.org/2/tutorial/classes.html#inheritance

答案 4 :(得分:0)

这意味着SearchAgentAStarFoodSearchAgent的基类。换句话说,AStarFoodSearchAgent继承自SearchAgent类。

请参阅Inheritance - Python tutorial