在Python中,我第一次尝试了类。当我使用这段代码时,我得到了第15行的错误“这个构造不带参数”。有人能告诉我问题出在哪里吗?
class Triangle:
def _init_(self,h,b):
self.h = h
self.b = b
author = 'No one has claimed this rectangle yet'
description = 'None'
def area(self):
return (self.h * self.b)/2
def description(self,text):
self.description = text
def author(self,text):
self.author = text
fred = Triangle(4,5)
print fred.area()
发布于 2016-03-18 01:59:11
您的错误在init函数中。它应该有两个下划线之前和之后像这样的__init__()
。
以下是正确的代码:
class Triangle:
def __init__(self,h,b):
self.h = h
self.b = b
author = 'No one has claimed this rectangle yet'
description = 'None'
def area(self):
return (self.h * self.b)/2
def description(self,text):
self.description = text
def author(self,text):
self.author = text
fred = Triangle(4,5)
print fred.area()
发布于 2016-03-18 01:58:21
您应该使用双下划线__
来表示__init__
def __init__(self, h, b):
发布于 2016-03-18 01:59:42
当构造函数应该定义为_init_
时,您已经将其定义为__init__
(注意双下划线)。Python没有看到您的__init__
(因为它的名称不正确),它只是假设一个默认的构造函数(它不带参数)。
https://stackoverflow.com/questions/36074799
复制相似问题