python类什么时候加self_我什么时候应该在Python中使用类和self方法?

我一直在尝试编写一个Python程序来计算一个点的位置,基于4个锚的距离。我决定把它算作4个圆的交点。在

我有一个问题不是关于算法,而是关于类在这种程序中的使用。我对OOP没有太多的经验。在这里使用类是真的有必要吗?或者它至少在任何方面改进了一个程序?在

我的代码是:import math

class Program():

def __init__(self, anchor_1, anchor_2, anchor_3, anchor_4, data):

self.anchor_1 = anchor_1

self.anchor_2 = anchor_2

self.anchor_3 = anchor_3

self.anchor_4 = anchor_4

def intersection(self, P1, P2, dist1, dist2):

PX = abs(P1[0]-P2[0])

PY = abs(P1[1]-P2[1])

d = math.sqrt(PX*PX+PY*PY)

if d < dist1+ dist2 and d > (abs(dist1-dist2)):

ex = (P2[0]-P1[0])/d

ey = (P2[1]-P1[1])/d

x = (dist1*dist1 - dist2*dist2 + d*d) / (2*d)

y = math.sqrt(dist1*dist1 - x*x)

P3 = ((P1[0] + x * ex - y * ey),(P1[1] + x*ey + y*ex))

P4 = ((P1[0] + x * ex + y * ey),(P1[1] + x*ey - y*ex))

return (P3,P4)

elif d == dist1 + dist2:

ex = (P2[0]-P1[0])/d

ey = (P2[1]-P1[1])/d

x = (dist1*dist1 - dist2*dist2 + d*d) / (2*d)

y = math.sqrt(dist1*dist1 - x*x)

P3 = ((P1[0] + x * ex + y * ey),(P1[1] + x*ey + y*ex))

return(P3, None)

else:

return (None, None)

def calc_point(self, my_list):

if len(my_list) != 5:

print("Wrong data")

else:

tag_id = my_list[0];

self.dist_1 = my_list[1];

self.dist_2 = my_list[2];

self.dist_3 = my_list[3];

self.dist_4 = my_list[4];

(self.X1, self.X2) = self.intersection(self.anchor_1, self.anchor_2, self.dist_1, self.dist_2)

(self.X3, self.X4) = self.intersection(self.anchor_1, self.anchor_3, self.dist_1, self.dist_3)

(self.X5, self.X6) = self.intersection(self.anchor_1, self.anchor_4, self.dist_1, self.dist_4)

with open('distances.txt') as f:

dist_to_anchor = f.readlines()

dist_to_anchor = [x.strip() for x in dist_to_anchor]

dist_to_anchor = [x.split() for x in dist_to_anchor]

for row in dist_to_anchor:

for k in range(0,5):

row[k] = float(row[k])

anchor_1= (1,1)

anchor_2 = (-1,1)

anchor_3 = (-1, -1)

anchor_4 = (1, -1)

My_program = Program (anchor_1, anchor_2, anchor_3, anchor_4, dist_to_anchor)

My_program.calc_point(dist_to_anchor[0])

print(My_program.X1)

print(My_program.X2)

print(My_program.X3)

print(My_program.X4)

print(My_program.X5)

print(My_program.X6)

而且,我不太明白我应该在哪里使用self关键字,以及在哪里不需要使用self关键字。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值