实例属性继承

时间:2019-10-30 17:00:42

标签: python python-3.x

我试图做到这一点,以便在创建Customer实例并指定要去的餐厅时,将Restaurant类的该实例的number_served实例属性增加去餐厅的客户数。 / p>

我不确定number_served是否应该是类或实例属性(我认为是类),并且我不确定如何将属性从Restaurant类继承到Customer类,以便增加它。

class Restaurant:



    def __init__(self,name,restaurant_type,cuisine_type):
        self.name = name 
        self.restaurant_type = restaurant_type
        self.cuisine_type = cuisine_type
        self.number_served = 0 


    def describe_restaurant(self):
        print(f"{self.name} is {self.restaurant_type} which serves {self.cuisine_type}.")

    def open_restaurant(self):
        print(f"{self.name} is open.")

    def get_number_served(self):
        print(f"{self.number_served} customers served at the {self.name} today.")

    def increment_number_served(self,num):
        self.number_served += num

class Customers(Restaurant):

    def __init__(self,where_eating,no_of_people):
        self.where_eating = where_eating
        self.no_of_people = no_of_people

    def go_eat(self):
        self.increment_number_served(self.no_of_people)

我基本上希望将餐厅实例的number_served属性增加一个从客户类实例到餐厅的顾客数量

1 个答案:

答案 0 :(得分:2)

客户不是餐厅的一种,因此此处的继承不合适。 go_eat方法应将Restaurant的实例作为参数。

class Restaurant:
    def __init__(self, name, restaurant_type, cuisine_type):
        self.name = name 
        self.restaurant_type = restaurant_type
        self.cuisine_type = cuisine_type
        self.number_served = 0 

    def describe_restaurant(self):
        print(f"{self.name} is {self.restaurant_type} which serves {self.cuisine_type}.")

    def open_restaurant(self):
        print(f"{self.name} is open.")

    def get_number_served(self):
        print(f"{self.number_served} customers served at the {self.name} today.")

    def increment_number_served(self,num):
        self.number_served += num


r = Restaurant("...", "...", "...")


class Customers:

    def __init__(self, no_of_people):
        self.no_of_people = no_of_people

    def go_eat(self, restaurant):
        restaurant.increment_number_served(self.no_of_people)


c = Customers(9)
c.go_eat(r)

如果您希望Customers不仅代表一组食客,而且代表去特定餐厅的一组食客,则将r传递给__init__

class Customers:

    def __init__(self, where, no_of_people):
        self.where = where
        self.no_of_people = no_of_people

    def go_eat(self):
        self.where.increment_number_served(self.no_of_people)


c = Customers(r, 9)
c.go_eat()