Python 3x类方法

时间:2014-11-19 11:04:28

标签: python class python-3.x subclass

我目前正在学习课程的基础知识,并提出了一些基本代码,如下所示:

class shape(object):
    def __init__(self, num_sides, type):
        self.num_sides = num_sides
        self.type = type

class square(shape):
    def __init__(self, side_length):
        self.num_sides = 4
        self.type = 'regular quadrilateral'
        self.side_length = side_length
    def perim():
        return side_length * 4
    def area():
        return side_length ** 2

class circle(shape):
    def __init__(self, radius):
        self.num_sides = 1
        self.type = 'ellipsis'
        self.radius = radius

现在,当我键入以下内容时:

shape1 = square(5)
shape1.perim()

我得到以下输出:

<bound method square.perim of <__main__.square object at 0x0000000003D5FB38>>
这是什么?我怎样才能让python真正返回广场的周边?

另外,我有另一个问题: 除了__init__()__str__()之外,是否存在任何类方法?如果是这样,你能列出来,以便我可以去研究它们吗?

3 个答案:

答案 0 :(得分:1)

使用self

访问实例变量
class square(shape):
    def __init__(self, side_length):
        self.num_sides = 4
        self.type = 'regular quadrilateral'
        self.side_length = side_length
    def perim(self):
        return self.side_length * 4
    def area(self):
        return self.side_length ** 2

答案 1 :(得分:1)

两件事,形状初始化的缩进和自我添加。到了perim和area方法。

class shape(object):
    def __init__(self, num_sides, type):
        self.num_sides = num_sides
        self.type = type

class square(shape):

    def __init__(self, side_length):
        self.num_sides = 4
        self.type = 'regular quadrilateral'
        self.side_length = side_length

    def perim(self):
        return self.side_length * 4
    def area(self):
        return self.side_length ** 2

class circle(shape):
    def __init__(self, radius):
        self.num_sides = 1
        self.type = 'ellipsis'
        self.radius = radius

shape1 = square(5)
print( shape1.perim())

答案 2 :(得分:1)

如图所示,你将遇到一些问题。如果您尝试将circle和square设置为子集的形状类,则需要缩进两个子类。另外,在圆圈和方形上,你真的不需要(形状)。还注意到我注释掉的不需要的东西。

这不是我发布的结果。类形状(对象):没有显示,子类没有缩进,我似乎无法让它显示出来

类形状(对象):     def init (self,num_sides,type):         #self.num_sides = num_sides         self.type = type

class square:

    def __init__(self, side_length):
        #self.num_sides = 4
        #self.type = 'regular quadrilateral'
        self.side_length = side_length

    def perim(self):
        return self.side_length * 4
    def area(self):
        return self.side_length ** 2

class circle: 
    def __init__(self, radius):
        #self.num_sides = 1
        #self.type = 'ellipsis'
        self.radius = radius

    def area (self):
        return 3.14 * self.radius ** 2



shape2 = circle (5)
print ('test of circle: ',shape2.area ())

shape1 = square(5)
print('test of square:  ', shape1.perim())