我在python中编写一个名为Circle的类。 现在作为类的一部分,我想定义方法,所以我做了但是当我运行程序时它崩溃并说它们没有被定义。我找不到问题。
class Circle():
""" Holds data on a circle in the plane """
def __init__(self,*args):
if isinstance(args[0],Point) and isinstance(args[1],(float,int)):
assert args[1]>0
self.center= args[0]
self.r= args[1]
else:
assert args[2]>0
self.a=args[0]
self.b=args[1]
self.center= Point(self.a,self.b)
self.r= args[2]
def __mul__(self,other):
assert isinstance(other,(float,int))
assert other>0
return Circle(self.center,self.r*other)
__rmul__= __mul__
def area(self):
return math.pi*self.r**2
def circumference(self):
return 2*self.r*math.pi
def move(self,p):
assert isinstance(p,Point)
self.center= p
return None
我为Point写了一堂课,所以这不是问题。 当我运行porgram时会发生这种情况:
>>> a=Circle(-3,-3,1)
>>> area(a)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
area(a)
NameError: name 'area' is not defined
答案 0 :(得分:1)
编辑:正如@jsbueno指出的那样,这不是导致错误消息的错误:
你的缩进是关闭的(def __mul__
左边应该是1个空格),因此Python认为你已经结束了你的类定义,只是定义了一些更多的函数(而不是类方法)。
此外,您应该将area
称为方法 - a.area()
,而不是area(a)
。
我做了一些改造 - 添加了一些注释,重命名了一些变量,通常是清理过来 - 现在可以正常工作了:
from math import pi
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Circle:
"""
Holds data on a circle in the plane
"""
def __init__(self, a, b, c=None):
if c is None:
# Circle(Point, scalar)
self.center = a
self.r = b
else:
# Circle(scalar, scalar, scalar)
self.center = Point(a, b)
self.r = c
@property
def r(self):
return self._r
@r.setter
def r(self, new_r):
assert new_r > 0
self._r = new_r
def __mul__(self, scale_by):
return Circle(self.center, self.r * scale_by)
__rmul__ = __mul__
def area(self):
return pi * self.r**2
def circumference(self):
return 2 * pi * self.r
def move(self, new_center):
self.center = new_center
然后
a = Circle(-3,-3,1)
print(a.area())
给出
3.141592653589793
这是正确的。
答案 1 :(得分:0)
类中的方法可供实例使用,但必须使用&#34;来调用它们作为实例的组件。&#34;运营商。
因此,在您的示例中,您应该使用
a = Circle()
a.area()
而不是
area(a)