python定义一个圆,Python语言中心的一个圆使用OOP

class Point:

def __init__(self, initX, initY):

""" Create a new point at the given coordinates. """

self.x = initX

self.y = initY

def getX(self):

return self.x

def getY(self):

return self.y

def distanceFromOrigin(self):

return ((self.x ** 2) + (self.y ** 2))** 0.5

def __str__(self):

return "x=" + str(self.x) + ", y=" + str(self.y)

def get_line_to(self, target):

mx = (-target.x + self.x )

my = (-target.y + self.y)

grad=my/mx

c=-(grad*(self.x))+self.y

return grad

def halfway(self, target):

"""calculating midpoint"""

mx = (self.x + target.x) / 2

my = (self.y + target.y) / 2

return Point(mx, my)

def cencd(p1,p2,p3):

"""calculating the center of a circle"""

ma=(p2.getY-p1.getY)/(p2.getX-p1.getX)

mb=(p3.getY-p2.getY)/(p3.getX-p2.getX)

hw=p1.halfway(p2)

x=(ma*mb*(p1.getY-p3.getY)+mb*(p1.getX+p2.getX)-ma*(p2.getX+p3.getX))/2*(mb-ma)

ya=-(1/ma)*((x-hw.getX)+hw.getY)

return x,ya

"""defining the points for p1,p2 and p3"""

p = Point(5,5)

q = Point(6,-2)

r=Point(2,-4)

print(cencd(p,q,r))

I get this error message:SyntaxError: duplicate argument 'p1' in function definition on

Traceback (most recent call last):

File "python", line 45, in

File "python", line 34, in cencd

TypeError: unsupported operand type(s) for -: 'method' and 'method'

please assist.

"""working solution """"

ma=(p2.y-p1.y)/(p2.x-p1.x)

mb=(p3.y-p2.y)/(p3.x-p2.x)

hw=p1.halfway(p2)

x1=(ma*mb*(p1.y-p3.y)+mb*(p1.x+p2.x)-ma*(p2.x+p3.x))/(2*(mb-ma))

ya=-(1/ma)*((x1-hw.x))+hw.y

解决方案

Both getX and getY are methods in your code, not attributes. So you will need to call them using getX() and getY().

So ma=(p2.getY-p1.getY)/(p2.getX-p1.getX) becomes:

ma = (p2.getY()-p1.getY())/(p2.getX()-p1.getX())

And so on, the other code changes.

Otherwise, you can also define your methods as @property:

class Point:

...

...

@property

def getX(self):

return self.x

@property

def getY(self):

return self.y

...

And now you can access these as p1.getX and p2.getY and so on.

Note that the above @property decorator turns the method into a getter, which makes sense to use only with private variables (variables defined to start with _).

As such, since both x and y are normal attributes of your class, you can access them directly without using and property decorators or using getter methods, like p1.x and p2.y, as @Padraic points in his post.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值