0

does objects have its methods or invoke them from superclass in python? for example:

class tst():
    def __init__(self,name,family):
        self.name=name
        self.family=family
        
    def fun(self,a,b):
        print(a+b)


newtst=tst("myname","my family")

tst.fun(newtst,3,5)
newtst.fun(3,5)

in the code above does newtst object invoke fun function from tst class or it has own method and run it directly and if the latter is true why we need to self parameter in definition class's functions and in know that id(newtst.fun) is different from id(tst.fun) but i think that differences is because of creating new method's object in memory.

2
  • newtst is an instance of tst. And you don't have to pass the instance object to fun method as it's first argument. Commented Apr 4, 2021 at 6:41
  • no it's true. try it yourself Commented Apr 4, 2021 at 6:46

1 Answer 1

1

Instance methods are implemented as descriptors in python. This implies, the separate instances are not keeping individual copies of method, but getting the same attribute of a different instances may produce individual results for each of them.

Despite we have the same function object beyond the attributes of all the instances we have, it still doesn't means that

id(tst.fun) == id(newtst.fun)

because method descriptor gives us different things when calling on a class and a class instance.

For a class we'll get an unbound method from tst, but for newtst it will be bound to an instance.

Sign up to request clarification or add additional context in comments.

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.