у меня проблема сделать наследовать от другого класса - PullRequest
0 голосов
/ 16 февраля 2019

Я только что создал три класса для наследования, но что-то пошло не так, но я пытаюсь решить это, но не работает
Я хочу знать, что делает это Ошибка и как я должен решить
Я должен унаследовать от других классов

  1. Классы:
    • Имущество
    • Дом
    • Аренда
    • HouseRental

почему House Object не принимает параметров

в Book python 3 объектно-ориентированного программирования

Это немного удивительно, поскольку у него нет ни init , ни метода отображения!Поскольку оба родительских класса соответствующим образом вызывают super в этих методах, нам нужно только расширить эти классы, и классы будут вести себя в правильном порядке.Конечно, это не относится к prompt_init, поскольку это статический метод, который не вызывает super, поэтому мы реализуем его явно.Мы должны проверить этот класс, чтобы убедиться, что он ведет себя правильно, прежде чем писать три другие комбинации:

def get_valid_input(input_string, valid_options):
    input_string += "({})".format(", ".join(valid_options))
    response = input(input_string)
    while response.lower() not in valid_options:
        response = input(input_string)
    return response

class Property:
    def __init__(self, baths="", square_feet="",
                 beds="", **kwargs):
        super().__init__(**kwargs)
        self.num_baths = baths
        self.square_feet = square_feet
        self.num_beds = beds

    def display(self):
        print("PROPERTY DETAILS")
        print("================")
        print("square footage: {}".format(self.square_feet))
        print("bedrooms: {}".format(self.num_bedrooms))
        print("bathrooms: {}".format(self.num_baths))
        print()

    @staticmethod
    def prompt_init():
        return dict(sqare_feet=input("Enter The Square:"),
                    num_beds=input("Enter the Number of beds"),
                    num_baths=input("Enter the Number of baths"),)
class House(Property):
    valid_garage = ("attached", "detached", "none")
    valid_fenced = ("yes", "no")

    def __init__(self, garage="", fenced="", num_stories="", **kwargs):
        super().__init__(**kwargs)
        self.num_stories = num_stories
        self.garage = garage
        self.fenced = fenced

    def display(self):
        super().display()
        print("HOUSE DETAILS")
        print("# of stories: {}".format(self.num_stories))
        print("garage: {}".format(self.garage))
        print("fenced yard: {}".format(self.fenced))

    @staticmethod
    def prompt_init():
        parent_init = Property.prompt_init()
        garage = get_valid_input("Is the yard fenced? ", House.valid_garage)
        fenced = get_valid_input("Is there a garage? ", House.valid_fenced)
        num_stories = input("How many stories? ")

        parent_init.update({
            "garage": garage,
            "fenced": fenced,
            "num_stories": num_stories
        })
        return parent_init
class Rental:
    def __init__(self, furnished="", rent="", utilities="", **kwargs):
        super().__init__(**kwargs)
        self.furnished = furnished
        self.rent = rent
        self.utilities = utilities

    def display(self):
        super().display()
        print("RENTAL DETAILS")
        print("rent: {}".format(self.rent))
        print("estimated utilities: {}".format(self.utilities))
        print("furnished: {}".format(self.furnished))

    @staticmethod
    def prompt_init():
        return dict(
                rent=input("What is the monthly rent? "),
                utilities=input("What are the estimated utilities? "),
                furnished=get_valid_input("Is the property furnished? ",       ("yes", "no")),)
class HouseRental(House, Rental):

    @staticmethod
    def prompt_init():
        init = House.prompt_init()
        init.update(Rental.prompt_init())
        return init

info = HouseRental().prompt_init()
o = HouseRental(**info)
o.display()
Traceback (most recent call last):
  File "estate/placement.py", line 148, in <module>
    o = HouseRental(**info)
  File "estate/placement.py", line 68, in __init__
    super().__init__(**kwargs)
  File "estate/placement.py", line 13, in __init__
    super().__init__(**kwargs)
  File "estate/placement.py", line 117, in __init__
    super().__init__(**kwargs)
TypeError: object.__init__() takes no parameters

1 Ответ

0 голосов
/ 16 февраля 2019

В классе Rental вы не указали родительский класс, но вызвали super ().

Должен ли Rental быть подклассом Property?

Если это так, простоизмените этот класс на:

class Rental(Property):
def __init__(self, furnished="", rent="", utilities="", **kwargs):
    super().__init__(**kwargs)
    self.furnished = furnished
    self.rent = rent
    self.utilities = utilities

Аналогично, свойство Property вызывает super (), но наследуется от родителя.Я не думаю, что вы намереваетесь, чтобы Property был подклассом, поэтому удалите вызов super ():

class Property:
def __init__(self, baths="", square_feet="",
             beds="", **kwargs):
    self.num_baths = baths
    self.square_feet = square_feet
    self.num_beds = beds

В более общем смысле: форма NewClass (ParentClass) побуждает NewClass наследовать методы и свойстваиз ParentClass.Любые аргументы, принятые функцией init класса Parent, теперь можно безопасно передавать в NewClass.Вызов super (). init (** kwargs) принимает все аргументы ключевого слова, переданные в NewClass, и передает их в ParentClass.

Если ParentClass отсутствует, то NewClass наследуется от PythonБазовый класс Object, который не принимает аргументов.Передача (** kwargs) в Object приводит к ошибке.

Последняя строка вашей трассировки описывает это:

object.__init__() takes no parameters
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...