如何在python中使用构造函数创建对象

2024-10-03 21:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

这个让我很难受。我需要使用我创建的类在主模块中创建一个对象。然而,根据我自己的经验,我们应该先在main中创建对象,然后才能从班上的同学们我需要创建的对象的名称将命名为(Customer1),该程序的总体思想是它是一个中餐馆的订购程序,代码如下所示。在

def Choose_dish(self):

    print('Please choose from the following items for a main dish:'
          'Sweet and Sour Pork, Sesame Chicken, or Shrimp Fried rice.')

    choice = input('Press 1 for Sweet and Sour, Press 2 for Sesame Chicken, or press 3 for Shrimp Fried rice.')

    if choice == 1:
        self._dish = 'sweet and sour'

    if choice ==2:
        self._dish = 'sesame chicken'

    if choice == 3:
        self._dish = 'shrimp fried rice'

第一个方法是protected构造函数,它被调用以便(Customer1)对象可以选择主盘。下面是我一直在尝试的代码。在

^{pr2}$

请注意,我创建的python类文件的名称是“Dinner_Combo”,类本身的名称是“Dinner_Combo”


Tags: and对象代码self程序名称forif
1条回答
网友
1楼 · 发布于 2024-10-03 21:33:04

你可以这样做:

class Dinner_combo(object):
    def __init__(self):
        self._dish = self.Choose_dish()

    def Choose_dish(self):
        print('Please choose from the following items for a main dish:'
              'Sweet and Sour Pork, Sesame Chicken, or Shrimp Fried rice.')
        choice = input('Press 1 for Sweet and Sour, Press 2 for Sesame Chicken, or press 3 for Shrimp Fried rice.')
        if choice == 1:
            return 'sweet and sour'
        elif choice == 2:
            return 'sesame chicken'
        elif choice == 3:
            return 'shrimp fried rice'

上面的内容应该有助于您在main中实现所需的行为,但我建议您重新评估您的方法:我通常会尽量避免任何可能在初始值设定项中崩溃的操作。在


初始值设定项(__init__(self, ...))是类的一种特殊方法,在对象创建后被称为“自动”。对象实际上已经存在,初始化器只是对其进行初始化。通常,除非调用它来初始化父类,否则不会显式调用它。在

来自https://docs.python.org/2/tutorial/classes.html#class-objects

The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:

^{pr2}$

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

相关问题 更多 >