Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:从_init__参数中选择类_Python_Inheritance_Instantiation - Fatal编程技术网

python:从_init__参数中选择类

python:从_init__参数中选择类,python,inheritance,instantiation,Python,Inheritance,Instantiation,设计这两个类的最符合Python的方式是什么: class Rectangle: def __init__(self,a,b): self.a = a self.b = b def area(self): return self.a*self.b class Square(Rectangle): def __init__(self,a): super().__init__(a,a) 返回一个prop

设计这两个类的最符合Python的方式是什么:

class Rectangle:

    def __init__(self,a,b):
        self.a = a
        self.b = b

    def area(self):
        return self.a*self.b

class Square(Rectangle):

    def __init__(self,a):
        super().__init__(a,a)

返回一个propper
Square
object?

即使您可以实现它,让类实例化返回您实例化的类以外的内容也不是一个好主意。相反,您也许可以使用工厂模式?例如,ShapeFactory类,其方法CreateShape将在这两个类之间进行选择,并返回矩形对象或方形对象?是的,尽管在Python中工厂本身不需要是类,但您可以使用
create\u shape()
作为一个独立函数。似乎更好。好的,我会试试的,谢谢你的提示。如果你能做到的话,让类实例化返回你实例化的类以外的东西不太可能是个好主意。相反,您也许可以使用工厂模式?例如,ShapeFactory类,其方法CreateShape将在这两个类之间进行选择,并返回矩形对象或方形对象?是的,尽管在Python中工厂本身不需要是类,但您可以使用
create\u shape()
作为一个独立函数。似乎更好。好的,我试试看谢谢你的提示
Rectangle(2,2)