【问题标题】:Class not running - getting no results [closed]类没有运行 - 没有结果[关闭]
【发布时间】:2021-07-15 21:11:15
【问题描述】:

我是 python 类的新手,我正在尝试运行此代码,但没有得到任何结果:

class Restaurant:
    def __init__(self, mascalzone, it_fusion):
        self.mascalzone = mascalzone
        self.it_fusion = it_fusion

    def describe_restaurant(self):
        print(f"this restaurant is Italian and is named: {self.mascalzone}")

    def open_restaurant(self):
        print(f"the restaurant {self.it_fusion} is open , please come in!")

        # make  instance below:
        restaurant = Restaurant('open', 9)

        # printing two attributes individually:
        print(f"this:{restaurant.it_fusion}")
        print(f"that:{restaurant.mascalzone}")

        # calling both methods:
        restaurant.describe_restaurant()
        restaurant.open_restaurant()

【问题讨论】:

  • 缩进很重要...
  • 这段代码除了定义一个类之外什么也没做。您必须创建它的实例并调用方法才能运行代码。
  • @KalusD。函数被调用,但它们缩进到第二个函数中
  • # make instance below开始的所有内容都需要在左边距。
  • 我猜 Uri 在创建问题时弄乱了缩进。提示:粘贴代码,标记它,然后按{} 按钮。

标签: python class methods attributes


【解决方案1】:

这不是类的工作方式。您的代码的第一部分应该是描述类,然后第二部分实际上是创建类的一个实例。所以要么你认为你必须在定义中定义类,要么你忘了缩进。

open_restaurant() 中,删除创建Restaurant 的实例并将其置于类定义之外。然后将调用这两种方法的代码也放在代码之外。您的其余代码都很好。

代码:

class Restaurant:
    def __init__(self, mascalzone, it_fusion):
        self.mascalzone = mascalzone
        self.it_fusion = it_fusion

    def describe_restaurant(self):
        print(f"this restaurant is Italian and is named: {self.mascalzone}")

    def open_restaurant(self):
        print(f"the restaurant {self.it_fusion} is open , please come in!")

restaurant = Restaurant('open', 9)
restaurant.open_restaurant()
restaurant.describe_restaurant()

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 2017-11-17
    • 2017-04-02
    • 1970-01-01
    • 2021-03-28
    • 2016-08-11
    相关资源
    最近更新 更多