简体   繁体   中英

How can I improve calling my methods/functions from a class in Python3?

I've got a class called Point with many functions. I put an extract code:

#/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))

When I call the functions I put this code:

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()

I put p.dist(q) and p.pto_medio(q) but I want to write dist(p, q) and pto_medio(p, q) , respectivily. I've seen several solutions about that but all solutions give me error.

Thanks!

I don't know why you want to do this… but if you want to, it's easy.

In Python, an unbound method (that is, a method accessed as a member of the class object) can be called just like a function, by passing the self argument explicitly. So:

dist = Point.dist
pto_medio = Point.pto_medio

dist(p, q)
pto_medio(p, q)

In other words, the unbound method is the function you def 'd in the class definition , with no magic whatsoever.*

If you want to know how this all works under the covers, see the Descriptor HOWTO and how methods work .


And there are plenty of cases where this is useful, beyond just adapting two pieces of code that were written incompatibly. For example, map and filter don't take a function, they take any callable. Sometimes it makes sense to pass them an unbound method:

with open(path) as f:
    strippedlines = map(str.strip, f)

If you couldn't pass unbound methods around like functions, you'd have to write that as:**

with open(path) as f:
    strippedlines = map(lambda line: line.strip(), f)

* In Python 2.x, this isn't true; an unbound method is instead a bound method with None for the bound instance, and there's special magic to make it work. But in 3.0+, unbound methods are just plain functions.

** Well, actually you could just use a comprehension: (line.strip() for line in f) . But if you wanted to use map , you'd have to build a wrapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM