首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >难以理解子类和super()函数中的__init__()

难以理解子类和super()函数中的__init__()
EN

Stack Overflow用户
提问于 2022-04-17 21:41:48
回答 1查看 577关注 0票数 2

我在理解Python中的这两个特定概念时遇到了一些困难。我觉得我明白他们的要旨,但不完全理解他们。

根据我收集的信息,super()从父类调用init方法,并处理从父类传递给它的参数。

那么,为什么子类中需要包含与超类中相同的参数的init方法呢?这是因为这两个类在本质上仍然是相似的,因此子类需要超类的一些基本特性吗?我知道大多数类都需要构造函数,只是想知道为什么需要在子类构造函数中重新定义与超类中相同的参数,并且在构造函数的主体中有一个超级()函数。

一个代码的前任,应该是这样的:

代码语言:javascript
复制
#9-6 Ice Cream Stand

class Restaurant:
    
    def __init__(self, restaurant_name, cuisine_type):
        """Set attributes of a restaurant"""
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        self.number_served = 0

    def describe_restaurant(self):
        """Print a statement about the restaurant"""
        print(f"Welcome to {self.restaurant_name.title()}! Enjoy our amazing {self.cuisine_type.title()} cuisine!")

    def open_restaurant(self):
        """Print a message indicating the restaurant is open"""
        print(f"{self.restaurant_name.title()} is open and ready to serve!")

    def set_number_served(self, total_served):
        self.number_served = total_served

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


class IceCreamStand(Restaurant):

    def __init__(self, restaurant_name, cuisine_type='ice cream'):#Same params as in superclass contructor
        """Initialize the attributes of the parent class
        Then initialize the attributes specific to an ice cream stand."""
        super().__init__(restaurant_name, cuisine_type)
        self.flavors = []

    def display_flavors(self):
        """Display the ice cream flavors"""      
        for flavor in self.flavors:
            print(f"- "  + f"{flavor}")

ic_stand1 = IceCreamStand('tasty ice cream')
ic_stand1.flavors = ['chocolate', 'vanilla', 'strawberry']
ic_stand1.display_flavors()

ic_stand1.describe_restaurant()

有人能帮我看一下这个吗,这样我就能更好地理解这些概念了吗?所有的帮助都是感激的。

EN

回答 1

Stack Overflow用户

发布于 2022-04-17 21:47:53

构建IceCreamStand的过程包括构造一个Resturant的过程,以及一些其他的东西(例如初始化flavours)。要构建Resturant,您需要restaurant_namecuisine_type

但是__init__ of IceCreamStand不知道你想要什么名字。就像Resturant要求您提供restaurant_name一样,IceCreamStand也是如此。

这里唯一奇怪的是,__init__ of IceCreamStand有一个cuisine_type默认为'ice cream'。这是没有意义的,因为它允许来电者说:

代码语言:javascript
复制
strange_icecream_stand = IceCreamStand("Strange icecream stand", cuisine_type = 'meat balls') # Meat balls ?!

相反,这样定义是有意义的:

代码语言:javascript
复制
class IceCreamStand(Restaurant):

    def __init__(self, restaurant_name)
        """Initialize the attributes of the parent class
        Then initialize the attributes specific to an ice cream stand."""
        super().__init__(restaurant_name, 'ice cream') # The `cuisine_type` is always ice cream now
        self.flavors = []

    # ...
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71905661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档