简体   繁体   中英

Three different Method calls of Python class

I am reading this article . In this article a line says :

For a Class C, an instance x of C and a method m of C the following three method calls are equivalent:

type(x).m(x, ...)

Cm(x, ...)

xm(...)

I tried to convert this statement into program like this :

class C:
    def __init__(self,a,c):
        self.a=a
        self.b=c

    def m(self):
        d=self.a+self.b

x=C(1,2)
x.m()
print(type(x).m(x))
print(C.m(x))
print(x.m())

But i am getting no clue what these three methods meant and how they are working ?? If my program is using method wrong then please correct it.

edit

I am not asking for modifications for this code , I am asking how those three methods are used and provide one example with each method calls.

If you can provide proper example for each three method that would be very helpful for me.

If using python 2.7, you should derive C from object in order to get the correct type with type(x) , which knows the method m .

class C(object):
    def __init__(self,a,c):
        self.a=a
        self.b=c

    def m(self):
        return self.a+self.b

x=C(1,2)
x.m()
print(type(x).m(x))
print(C.m(x))
print(x.m())

I think in python 3, this is implicit. And yes, instead of calculating d, I just return the result - so you see something.

Edit regarding your clarification:

The three ways to call the method are shown for illustration. I would not see any obvious reason for not using xm() if possible. But in python, that is a shortcut for: Call the method m of the type of x on the instance x . The type(x).m(x) is the most literal way to write what is going on. Now, type(x) is C (in python 3 or with new-style classes - derived from object - at least, else instance), so the first and second way of writing are equivalent as well.

Your m isn't returning anything.

You want

def m(self):
    return self.a + self.b

Most likely within your C class

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