python - 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?我完全不明白到底发生了什么以及它是如何工作的。提前致谢!
解决方案
如所写,您有责任将结果传递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()
推荐阅读
- google-cloud-platform - Google Identity Platform 存储的数据的位置
- c++ - 编译时架构 i386 的未定义符号
- angular - Karma 测试 Angular - TypeError:无法读取 null 的属性“recipientAddressId”
- python - Azure 搜索 - 创建索引 - JSON 解码错误
- javascript - 从数据库回调中发出事件
- sql - 如何加入表并以 JSON 格式返回?
- python - 如何搜索给定 .txt 文件的每个“the”
- python - 如何在失败时恢复 Prefect 流程而无需重新运行整个流程?
- sql-server - SSIS:迁移到 Azure VM 后出现 AcquireConnection 错误
- java - 在 android studio 中使用 RecyclerView 但没有打印任何内容