我有一个名为Point的类,有许多功能。我提了一个提取代码:
#/usr/bin/env python3
# -*- coding: utf-8 -*-
from math import sqrt, pow, hypot, atan2, cos, sin
class Point(object):
__slots__ = ['x', 'y', 'z']
def __init__(self, x=0, y=0, z=None):
self.x = x
self.y = y
self.z = z
def __del__(self):
#del P destroy (delete) a point
class_name = self.__class__.__name__
def dist(self, P):
if self.z is not None:
d = sqrt(pow(self.x - P.x, 2) + pow(self.y - P.y, 2) +
pow(self.z - P.z, 2))
return d
else:
d = sqrt(pow(self.x - P.x, 2) + pow(self.y - P.y, 2))
return d
def pto_medio(self, P):
Q = Point(self.x, self.y)
if self.z is not None:
Q = Point(self.x, self.y, self.z)
else:
Q = Point(self.x, self.y)
R = (1. / 2.) * (P + Q)
return R
def entrada(self):
point = raw_input('Introduce un punto:\n')
point = point.replace('(', '')
point = point.replace(')', '')
l1 = point.rsplit(',')
self.x = float(l1[0])
self.y = float(l1[1])
if len(l1) == 3:
self.z = float(l1[2])
l1 = []
def __repr__(self):
if self.z is not None:
return('({}, {}, {})'.format(self.x, self.y, self.z))
else:
return('({}, {})'.format(self.x, self.y))
当我调用这些函数时,我把这段代码:
def main():
p = Point()
q = Point()
Point.entrada(p)
Point.entrada(q)
s = p + q
r = p - q
m = 5 * p
print(('Distancia = {}'.format(p.dist(q))))
print(('Punto Medio = {}'.format(p.pto_medio(q))))
if __name__ == '__main__':
main()
我把 p.dist(q)和 p.pto_medio(q)但是我想写 dist(p,q)和 pto_medio(p,q),分别。我已经看到了几个解决方案,但所有解决方案都给我错误。
谢谢!
答案 0 :(得分:2)
我不知道为什么你想要这样做......但如果你愿意,那很容易。
在Python中,通过明确传递self
参数,可以像函数一样调用未绑定方法(即作为类对象成员访问的方法)。所以:
dist = Point.dist
pto_medio = Point.pto_medio
dist(p, q)
pto_medio(p, q)
换句话说,未绑定的方法是你在类定义中def
'的函数,没有任何魔法。*
如果您想知道这一切是如何运作的,请参阅Descriptor HOWTO和how methods work。
并且有很多情况下这是有用的,除了调整两个不兼容的代码之外。例如,map
和filter
不接受函数,它们接受任何可调用的函数。有时将它们传递给未绑定的方法是有意义的:
with open(path) as f:
strippedlines = map(str.strip, f)
如果您无法像函数那样传递未绑定的方法,则必须将其写为:**
with open(path) as f:
strippedlines = map(lambda line: line.strip(), f)
*在Python 2.x中,这不是真的;对于绑定的实例,未绑定的方法是None
的绑定方法,并且有一些特殊的魔法可以使它工作。但是在3.0+中,未绑定的方法只是简单的函数。
**嗯,实际上你可以使用一种理解:(line.strip() for line in f)
。但是如果你想使用map
,你必须构建一个包装器。