0
class Run(object):

    def run(self):
        print('run, save yourself')

Run().run()

it prints out

'run, save yourself'

How can we run class and its functions without defining object to it?

We have to assign an object to the class and then run it like

r = Run()

r.run()

Does python automatically assigns the abject to Class and then runs it ?

Hritwik
  • 13
  • 4

2 Answers2

3

Here is what happens when you run Run().run():

1- Run() creates a Run object
2- in turn, this objects calls its method run() on itself

This is equivalent to:

r = Run()
r.run()

Except that in your case, your object Run() is created, then immediately garbage collected because there is nothing pointing to it, after the run() method was executed.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • so we can directly run class functions inside any class without assigning it to an object, python will temporarily make an object and then delete it? – Hritwik Sep 13 '17 at 14:38
  • yes, you can create "throwaway" objects, not assigned to any variables, and directly call a method on them. – Reblochon Masque Sep 13 '17 at 14:42
1

If you want a class to run without having to call run, you could try something like this

class Run(object):
    def __init__(self):
        self.run()

    def run(self):
        print('run, save yourself')

Run()
>>> run, save yourself

Expanding on that, you can also do

class Run(object):
    def __call__(self):
        self.run()

    def run(self):
        print('run, save yourself')

r = Run()
r()
>>> run, save yourself
bphi
  • 3,115
  • 3
  • 23
  • 36