0

In below example, the object of random is not created

from random import randint

print(randint(0, 10))

the definition of the randint function is as follow

import _random

class Random(_random.Random):
     def randint(self, a, b):
        return self.randrange(a, b+1)

Now in my case:

class XYZ:
     def func(self):
         do something

to call func, I have to create object of XYZ and then call function XYZ().func()else it throws error...

But I want to do it like

XYZ.func()

simply like how standard library function works. is there any way to achieve this?

2 Answers 2

2

The random module defines an instance of Random at the module level:

# Line 786
_inst = Random()

and random.randint is just a reference to a bound method for that instance:

# Line 791
randint = _inst.randint
Sign up to request clarification or add additional context in comments.

Comments

0

You wrote this:

class XYZ:
     def func(self):
         do something

You want this:

class XYZ:
     @classmethod
     def func(cls):
         do something

(or use @staticmethod if you prefer).

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.