首页 > 解决方案 > OOP 中的 staticmethod 和 __init__

问题描述

早上好,我正在阅读 Dusty Phillips - Python 3 Object Oriented Programming 一书。有一个类的例子

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

    def display(self):
        print("PROPERTY DETAILS")
        print(f'square footage: {self.square_feet}')
        print(f'bedrooms: {self.num_beds}')
        print(f'baths: {self.num_baths}')
        print()
    @staticmethod
    def prompt_init():
        return dict(square_feet=input("Enter the square feet: "),beds=input("Enter number of bedrooms: "),baths=input("Enter number of baths: "))

和 prompt_init 的信息 - “此方法使用 Python dict 构造函数创建可以传递给init的值字典。每个键的值都会通过调用输入来提示。” 问题是,作为 staticmethod 的方法 prompt_init 如何将变量传递给init?我完全不明白到底发生了什么以及它是如何工作的。提前致谢!

标签: pythonoop

解决方案


如所写,您有责任将结果传递dict__init__

 args = Property.prompt_init()
 p = Property(**args)

可以为您执行此操作的类方法会更合适:

class Property:
    def __init__(...):
        ...  # As before

    @classmethod
    def from_user_input(cls):
        square_feet = input("Enter the square feet: ")
        beds = input("Enter number of bedrooms: ")
        baths = input("Enter number of baths: ")
        return cls(square_feet, beds, baths)

p = Property.from_user_input()

推荐阅读