Kandan Siva
Kandan Siva

Reputation: 479

Python- Function object in class

class new:
    i=1
    def __init__(self):
        name='sakthi'

    def add(self,one,two):
         return one+two

k=new.add

print(k)

When I execute the above program. I get function new.add at 0x0068E270 as output.

Can anyone help me to understand, what has happened and what kind of operation can I do with value k.

Upvotes: 0

Views: 37

Answers (2)

E_K
E_K

Reputation: 2249

function new.add at 0x0068E270 In CPython, will be the address of k. Since k is just a function you can still do something like print(k('foo', 1, 2)) that Will print 5

Upvotes: 1

Blckknght
Blckknght

Reputation: 104852

The new.add value you're assigning to k is a function. In Python 2, it would have been a special "unbound method" object, but your output suggests you're using Python 3 (where unbound methods don't exist any more except conceptually).

Like any function, you can call k if you want, passing whatever values are appropriate for self, one and two. For instance, k("foo", 1, 2) (which will return 3).

Traditionally the self argument should be an instance of the new class, though in Python 3 that isn't enforced by anything (a check for this was the purpose of unbound method objects in Python 2). So passing a string in the example above worked fine, since self is not used in the function body for anything. (More complicated methods will usually fail if you pass an inappropriate argument as self.)

The usual way to call methods is to create an instance of a class first, then call the method on the instance. This causes the instance to be passed as the first argument automatically:

x = new()
x.add(1, 2) # returns 3, x got passed as self

Upvotes: 1

Related Questions