简体   繁体   中英

How to call functions/methods inside objects in python

Here is my code.

How do I execute the print_point line? Edited to work. Thank you

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def distance_from_origin(self):
        return ((self.x **2) + (self.y **2)) **.5
    def print_point(p):
        print '(%s, %s)' % (str(p.x), str(p.y))

Here is what I type into the shell after running module:

p = Point(5,2)

p.x

    5

p.y

    2

p.distance_from_origin()

    5.385164807134504

p.print_point(p)

    Traceback (most recent call last):
    File "<pyshell#196>", line 1, in <module>
    p.print_point(p)
    TypeError: print_point() takes exactly 1 argument (2 given)

It's not clear what you want, since you've got the indentation wrong. Is print_point part of the class?

If so, you got self right in distance_from_origin , but perhaps not in print_point :

def print_point(self):
    print '(%f, %f)' % (self.x, self.y)

It is legal, but a bad idea , to use a different name for the self parameter such as your p .

(And note that the very act of printing will do the str conversion for you...)

Or did you want print_point to be out of the class, in which case you should have it as is but with (px, py) ? Or, as suggested by other answers, a static or class method?

Add self as the first argument or print_point . You'll also need to reference x and y using the self prefix because those fields belong to the instance.

def print_point(self):
     print '(%s, %s)' % (str(self.x), str(self.y))

You used self as a parameter in the function distance_from_origin .

But you chose p as a parameter in the function print_point .

Actually, it works with p :

>>> p = Point(5,2)
>>> p.print_point()
(5, 2)

But there is a convention to use self for passing the instance of the class to the method. Otherwise everything gets very cumbersome.

Also, %s converts the object to string using str method. So, there is no need to convert in manually to string.

Taking it all into account, the function print_point will look like:

def print_point(self):
    print '(%s, %s)' % (self.x, self.y)

Point coordinates are represented by numbers so you may want to use special method for number output.

There is a new format method for string. It definitely exists in Python 2.7 . Just look at the examples and choose the most satisfactory output format for your case. For example you may do this:

def print_point(self):
    print('({self.x}, {self.y})'.format(self=self))

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