【问题标题】:Inheritance about shapes with python用python继承形状
【发布时间】:2019-11-07 21:03:15
【问题描述】:

我要写四个类:平行四边形、矩形、菱形和正方形。 init 方法的参数应始终按以下顺序输入:(base、side、theta),并非每个类的 init 都会采用所有三个。因此,例如,一个 Rectangle 将只取 (base, side)。这些类的对象必须具有以下方法: area() - 返回形状的面积 平行四边形的面积由底边 sin(theta) 计算。看看函数 math.radians 在度数和弧度之间进行转换。 bst() - 返回三个燕麦的列表:[base, side, theta]。即使形状不需要其中一个参数作为输入,它仍然应该能够返回它。 (例如,一个 10 x 10 的正方形将返回:[10, 10, 90])。打印时,每个形状都应返回一个带有以下格式的文本的字符串 \I am a shape with area area"。四个示例,一个 10 x 10 的正方形将返回字符串:\I am a Square with area 100"。这是我到目前为止所拥有的 http://pastebin.com/CkGndsRU

【问题讨论】:

  • 在这里发布您的代码和您的问题,无需提供链接...
  • 顺便问一下你有什么问题?
  • 我只想问如何使用继承来减少我的代码重复
  • 我想你在下面的答案中得到了一个例子,对你来说足够好吗?
  • 我在代码中也犯了一些错误,导致它无法工作,所以你们能告诉我如何解决它

标签: python class inheritance shape


【解决方案1】:

无需使用参数调用 super...这是另一个继承示例 - 形状...

编辑:我讨厌这个网站如何将 python 代码转换为使用空格而不是制表符......这是一个令人作呕的习惯,它以惊人的速度增加文件大小......

我在这个线程中的另一个示例的基础上添加了一些示例(区域函数和tostring方法)

# --
# -- Basic example of classes and inheritance by using an easy to follow idea - shapes - and extending them.. - Josh 'Acecool' Moser
# --


# --
# -- Shape Base-Class - This only holds the name of the object and nothing else...
# --
class Shape:
    # -- Class Vars
    name = "Shape"


    # --
    # -- The ToString function for this class - it is what is called when you print( str( shape ) )
    # -- Note: You need to use str( x ) to convert that object to a string - most data-types have an appropriate To-String function to do this and if not you'll be left with something like <address / reference / other info>
    # --
    def __str__( self ):
        return "I am a " + self.name + " defined as " + type( self ).__name__ + "( ... )"


# --
# -- Square extends Shape - A Square has the same width / height so we only need 1 value, we'll use X but it can be anything we want..
# --
class Square( Shape ):
    # -- Class Vars
    name = "Square"

    # -- Set x to a default value
    x = 0


    # --
    # -- Object Creation - We'll use this to create a square: Square( 10 ) for example.
    # --
    def __init__( self, _x ):
        # -- Run the BaseClass - Although Shape doesn't do anything, it's here to fall all the way through just in case...
        super( ).__init__( )

        # -- We can set the name here, or just leave it in the class - Note: The same can be done in Rect but I omitted it to keep this example short...
        # -- self.name = "Square"

        # -- Update X for this instance - Note: I'd typically use a Getter / Setter for all variables to prevent incorrect data-types or usage
        self.x = _x


    # --
    # -- The ToString function for this class - it is what is called when you print( str( shape ) )
    # -- Note: You need to use str( x ) to convert that object to a string - most data-types have an appropriate To-String function to do this and if not you'll be left with something like <address / reference / other info>
    # --
    def __str__( self ):
        return "I am a " + self.name + " defined as " + type( self ).__name__ + "( " + str( self.x ) + " ) ie x = " + str( self.x ) + " with an area of " + str( self.area( ) )


    # --
    # --
    # --
    def area( self ):
        return self.x * self.x


# --
# -- Cube extends Shape - This cube is coded to change a few of the functions from Square - it is also coded as a 1 var shape, ie all sides are the same..
# --
class Cube( Square ):
    # -- Class Vars
    name = "Cube"


    # --
    # -- Object Creation - We'll use this to create a square: Square( 10 ) for example.
    # --
    def __init__( self, _x ):
        # -- Run the BaseClass - Although Shape doesn't do anything, it's here to fall all the way through just in case...
        super( ).__init__( _x )


    # --
    # -- The ToString function for this class - it is what is called when you print( str( shape ) )
    # -- Note: You need to use str( x ) to convert that object to a string - most data-types have an appropriate To-String function to do this and if not you'll be left with something like <address / reference / other info>
    # --
    def __str__( self ):
        return super( ).__str__( ) + " with an area of " + str( self.area( ) )


    # --
    # --
    # --
    def area( self ):
        return self.x ** self.x


# --
# -- Rectangle extends Square extends Shape ( Same as class Rect( Square, Shape ) but Square extends Shape so it shouldn't be needed for fallthrough )
# -- A Rectangle has different width and height so we'll use x from square for width, and add y for height to make a rectangle...
# --
class Rect( Square ):
    # -- Class Vars
    name = "Rectangle"

    # -- Set y to a default value so we don't need to worry about errors if it isn't defined
    y = 0


    # --
    # -- Object Creation - We'll use this to create a rectangle: Rect( 10, 20 ) for example.
    # --
    def __init__( self, _x, _y ):
        # -- Run the BaseClass - This is needed to set self.x by allowing Square to execute that - we could also do self.x = x, but this is an example of inheritance so...
        super( ).__init__( _x )

        # -- Update y for this instance - Note: I'd typically use a Getter / Setter for all variables to prevent incorrect data-types or usage - but to keep things short, I kept things simple...
        self.y = _y


    # --
    # -- The ToString function for this class - it is what is called when you print( str( shape ) )
    # -- Note: You need to use str( x ) to convert that object to a string - most data-types have an appropriate To-String function to do this and if not you'll be left with something like <address / reference / other info>
    # --
    def __str__( self ):
        return "I am a " + self.name + " defined as " + type( self ).__name__ + "( " + str( self.x ) + ", " + str( self.y ) + " ) ie x = " + str( self.x ) + " / y = " + str( self.y ) + " with an area of " + str( self.area( ) )


    # --
    # --
    # --
    def area( self ):
        return self.x * self.y


# --
# -- Main
# --
def main( ):
    # -- Create a rectangle with x = 10, y = 20
    _shape = Rect( 10, 20 )

    # -- Create a rectangle with x = 30, y = 40
    _shape2 = Rect( 30, 40 )

    # -- Create a square with x = 50
    _shape3 = Square( 50 )

    # -- Create a simple Shape - with nothing attached...
    _shape4 = Shape( )

    # -- Create a simple Cube...
    _shape5 = Cube( 4 )

    # --
    # -- I'm doing the output text here so you know that declaring other shapes won't overwrite other values in other objects
    # -- if I were set up the output text after each object creation and allow another object to be created afterwards
    # --    it wouldn't prove that the objects have their own values meaning it would be possible for the variables to be
    # --    static ( shared among all types so the last object to update that value would mean all objects have that value )
    # --    but, by having all text here, it shows that the variables aren't static - they're private..
    # --
    # -- Note: I left the original outputs commented to the right of the new str( object ) method so you could see one way of doing it vs the benefits of having a __str__ ToString method handle it for you...
    # --

    # Define the text output var... Then add to it for each line...
    _text = ""

    # -- This is calling Rect ToString function normally
    # -- Originals output without using tostring method -- # _text += _shape.name + " x: " + str( _shape.x ) + " y: " + str( _shape.y ) + "\n"
    _text += str( _shape ) + "\n"

    # -- This is calling Square ToString function ( ie super of Rect is Square ) -- Output: I am a Rectangle defined as Rect( 10 ) ie x = 10
    _text += str( super( Rect, _shape ).__str__( ) ) + "\n"

    # -- This is calling Shape ToString function ( ie super of Square is Shape ) -- Output: I am a Rectangle defined as Rect( ... )
    _text += str( super( Square, _shape ).__str__( ) ) + "\n"

    # -- This calls Rect ToString function normally
    # -- Originals output without using tostring method -- # _text += _shape2.name + " x: " + str( _shape2.x ) + " y: " + str( _shape2.y ) + "\n"
    _text += str( _shape2 ) + "\n"

    # -- This calls Square ToString function normally
    # -- Originals output without using tostring method -- # _text += _shape3.name + " x: " + str( _shape3.x ) + "\n"
    _text += str( _shape3 ) + "\n"

    # -- This calls Shape ToString function normally
    _text += str( _shape4 ) + "\n"

    # -- This calls Shape ToString function normally
    _text += str( _shape5 ) + "\n"

    # -- Output:
    # I am a Rectangle defined as Rect( 10, 20 ) ie x = 10 / y = 20 with an area of 200
    # I am a Rectangle defined as Rect( 10 ) ie x = 10 with an area of 200
    # I am a Rectangle defined as Rect( ... )
    # I am a Rectangle defined as Rect( 30, 40 ) ie x = 30 / y = 40 with an area of 1200
    # I am a Square defined as Square( 50 ) ie x = 50 with an area of 2500
    # I am a Shape defined as Shape( ... )
    # I am a Cube defined as Cube( 4 ) ie x = 4 with an area of 256 with an area of 256
    return _text


# --
# -- Call main and print the return contents...
# --
print( main( ) )

【讨论】:

    【解决方案2】:

    当每个类的某些组件相同时,继承很有用,因此您可以将它们包含在父类中,而不必在每个类中重新重写它们。查看您的代码,类的唯一相同之处是基本实例属性,因此您无法将很多内容放入父类中。

    这是一个类似的继承示例

    class square:
    
        def __init__(self, sidelen):
            self.sidelen = sidelen
        def area(self):
            return self.sidelen**2
    
    class cube(square):
    
        def area(self):
            return self.sidelen**3
    

    这里,cube 类从 square 类继承了它的 init 方法,但是覆盖了它的 area 方法。

    【讨论】:

    • 另外,我的代码似乎有问题,您可以看看我做错了哪一部分
    【解决方案3】:

    这是您的代码中的一个工作示例,用于演示 class and inheritance

    import math
    
    class Shape(object):        
        def __init__(self,base,side,theta=90):
            self.base=base
            self.side=side
            self.theta=theta
    
        def area(self):
            return self.base*self.side*math.sin(math.radians(self.theta))
    
        def bst(self):
            return [self.base, self.side, self.theta]
    
        def __str__(self):
            return 'I am a %s with area of %d' % (type(self).__name__, self.area())
    
    class Rectangle(Shape):     
        def __init__(self, base, side):
            super(Rectangle, self).__init__(base,side)
    
    
    class Square(Shape):       
        def __init__(self, base):
            super(Square, self).__init__(base,base)
    
    
    class Rhombus(Shape):       
        def __init__(self, base, theta):
            super(Rhombus, self).__init__(base,base,theta)
    
    class Parallelogram(Shape):       
        def __init__(self, base, side, theta):
            super(Parallelogram, self).__init__(base,side,theta) 
    

    注意:我在上面的例子中使用的是 Python2.7

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 2013-03-15
      • 2010-12-26
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      相关资源
      最近更新 更多