0
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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. I am using python 3
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.