Python Forum

Full Version: instance methods invokation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
The function is not referenced in the instance object, it is only referenced in the class object. The call tst.fun(3, 5) is incorrect here because fun() needs an instance to work. You can call newtst.fun(3, 5)
(Apr-04-2021, 07:05 AM)Gribouillis Wrote: [ -> ]The call tst.fun(3, 5) is incorrect here because fun() needs an instance to work
Yet the code gives no error:
Output:
8 8
I believe Mim has a point.
Also a class does not need an instance to work as we can read in 9.3.2. Class Objects: Class objects support two kinds of operations: attribute references and instantiation. As a method is also an attribute it can be called.
I thought your line 13 above was tst.fun(3, 5) which is incorrect. I may have misread it. As long as you provide the instance newtst, the call works.