Как я могу снять функцию open_restaurant ()? - PullRequest
0 голосов
/ 24 апреля 2019

Мне нужно снять функцию в классе. Я пытался набрать имя функции, но получил ошибку: NameError: name 'open_restaurant' is not defined

class Restaurant():
   """описание ресторана"""

def __init__(self, restaurant_name, cuisine_type):
    """Инициализирует атрибуты restaurant_name и cuisine_type."""
    self.restaurant_name = restaurant_name
    self.cuisine_type = cuisine_type

def describe_restaurant(self):
    print(self.restaurant_name.title())
    print(self.cuisine_type.title())

def open_restaurant():
    print("Restaurant is open now!")

class Restaurant():
restaurant = Restaurant("Amarcord", "Italian")
print("Today I will eat in " + restaurant.restaurant_name + ".")
print(restaurant.restaurant_name + " is an " + restaurant.cuisine_type + ".")
open_restaurant()

print("\nToday I will eat in " + restaurant.restaurant_name + ", it" + " is an " 
+ restaurant.cuisine_type + ".")

1 Ответ

2 голосов
/ 24 апреля 2019

Этот код сбивает меня с толку.Почему вы переопределяете Restaurant?Это должно работать:

class Restaurant:
   """описание ресторана"""

    def __init__(self, restaurant_name, cuisine_type):
        """Инициализирует атрибуты restaurant_name и cuisine_type."""
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self):
        print(self.restaurant_name.title())
        print(self.cuisine_type.title())

    def open_restaurant(self):
        print("Restaurant is open now!")

Мы определили класс.Давайте создадим его экземпляр:

r = Restaurant('x', 'y')

Теперь давайте вызовем определенный метод:

r.open_restaurant()  # Restaurant is open now!

И наоборот, если вы хотите вызвать open_restaurant() без создания экземпляра класса, вы можете определить @staticmethod:

class Restaurant:
   """описание ресторана"""

    def __init__(self, restaurant_name, cuisine_type):
        """Инициализирует атрибуты restaurant_name и cuisine_type."""
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self):
        print(self.restaurant_name.title())
        print(self.cuisine_type.title())

    @staticmethod
    def open_restaurant():
        print("Restaurant is open now!")

И тогда вы можете просто позвонить:

open_restaurant()  # Restaurant is open now!
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...