call class python code example

Example 1: call instance class python

# define class
class example:
# define __call__ function
   def __call__(self):
       print("It worked!")
# create instance
g = example()
# when attempting to call instance of class it will call the __class method
g()
# prints It worked!

Example 2: class methods parameters python

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

Example 3: python call function in class

#------------------------------------
#CLASS
#------------------------------------
class Student:
  def __init__(self):
    self.name = None
    
  def set_name(self, word):
    self.name = word
    return self.get_name()
    
  def get_name(self):
    return self.name
  
#------------------------------------
# USAGE:
#------------------------------------

a = Student()
print(a.set_name("Hello"))

Example 4: call a function from another class python

class A:
    def method1(arg1, arg2):
        # do code here

class B:
    A.method1(1,2)