python - 如何通过在__init__中获取用户输入来使用类计算矩形的面积
问题描述
""" 正如你所看到的,我正在尝试使用我想要获取用户输入的类来找出矩形的区域,但是第 22 行出现问题 """ from abc import ABC, abstractmethod #just practice about abstractmethod which i今天学习
class shape(ABC):
@abstractmethod
def printdetail(self):
return 0
class Area(shape):
def __init__(self,length,breadth):
self.length = length
self.breadth = breadth
def printdetail(self):
return self.breadth * self.length
@classmethod
def userinput(cls):
length = int(input("enter a length")) #taking user input as length of rectangle
breadth = int(input("enter a breadth "))#taking user input as breadth of rectangle
rect= Area.userinput()
ans=rect.printdetail()
print(ans)
"""error- ans=rect.printdetail() AttributeError: 'NoneType' object has no attribute 'printdetail' """
解决方案
您的类方法正在获取输入,但从不创建Area
要返回的实例。
@classmethod
def userinput(cls):
length = int(input("enter a length")) #taking user input as length of rectangle
breadth = int(input("enter a breadth "))#taking user input as breadth of rectangle
return cls(length, breadth)
推荐阅读
- python - 如何根据 Python 3 中另一个列表的长度动态创建列表
- arrays - 如何在 Google 表格中选择包含通过自定义公式过滤的某些单词的行
- python - 将多维数组乘以一维数组Python
- android - 当我制作构建 apk 时,GitHub Desktop 不会检测到更改?
- javascript - 在设置 document.getElementById 和 sessionStorage.setItem 时遇到问题
- c# - 如何从泛型接口获取方法传递给泛型类?
- css - Font Awesome 5 - 为什么调整字体系列时图标会消失?
- java - 如何在 Eclipse 中自定义“新”选项
- c# - 是否有任何适当的方法可以从通过某些特定字符串值搜索的 OLEDB 连接中检索数据?
- android - 无法更改 Android 虚拟设备 (AVD) 上的文件权限