Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
instance methods invokation
#1
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
Reply
#2
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)
Reply
#3
(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.
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  instance methods mim 7 3,346 Mar-28-2021, 03:46 PM
Last Post: deanhystad
  instance methods sharing addresses mim 1 2,293 Mar-28-2021, 05:22 AM
Last Post: deanhystad
  Class object instance. Link instance attribute to class. Can it be done easier. Windspar 7 4,314 Dec-03-2018, 11:16 PM
Last Post: Windspar
  How to check if class instance exists in a list of class instance objects? sonicblind 23 20,775 May-27-2018, 05:44 AM
Last Post: buran
  Python3x running only with one instance (how can I prevent too many running instance) harun2525 5 18,460 Jul-21-2017, 07:36 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020