从派生类派生一个类

时间:2016-04-17 15:02:40

标签: python class python-3.x

我有3个班级(CityNeighborhoodBlock)。

以下是City类的定义:

class City:
    def __init__(self, id_city, name_city):
        self.__id = id_city
        self.__name = name_city

Neighborhood

的定义
class Neighborhood(City):
    def __init__(self, id_neighborhood, name_neighborhood, number_block, *city_args, **kwargs):
        City.__init__(self, *city_args, **kwargs)
        self.__id = id_neighborhood
        self.__name = name_neighborhood
        self.__number = number_block

Block

的定义
class Block(Neighborhood):
    def __init__(self, id_block, number_block, number_flats, *neighborhood_args, **kwargs):
        Neighborhood.__init__(*neighborhood_args, **kwargs)
        self.__id = id_block
        self.__number_b = number_block
        self.__number_f = number_flats

然后我宣布实体:

city = City(5, "New York")
neighborhood = Neighborhood(1, "Brooklyn", 500, 5, "New York")
block = Block(11, 2, 20, 1, "Brooklyn", 500, 5, "New York")

并收到此错误:

AttributeError: 'int' object has no attribute '_City__id'

1 个答案:

答案 0 :(得分:1)

您忘记在self实施中传递Block.__init__()

Neighborhood.__init__(*neighborhood_args, **kwargs)

所以传入的第一个参数是整数。现在Neighbourhood.__init__()已将self绑定到1,您就会收到错误消息。只需添加self

class Block(Neighborhood):
    def __init__(self, id_block, number_block, number_flats, *neighborhood_args, **kwargs):
        Neighborhood.__init__(self, *neighborhood_args, **kwargs)