首页 > 解决方案 > 如何通过在__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' """

标签: pythonclassuser-input

解决方案


您的类方法正在获取输入,但从不创建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)

推荐阅读