Home > Enterprise >  OOP - Python - printing instance variable too when I call static method alone
OOP - Python - printing instance variable too when I call static method alone

Time:04-27

Here in this code I am just calling out my static method, but it prints my instance variable too. Could you please explain the reason for that, and how to avoid them being printed?

Like below:

I am a static Method

None

class Player:
    
     def __init__(self, name = None):
        self.name = name # creating instance variables
         
     @staticmethod
     def demo():
         print("I am a static Method")
         
p1 = Player()

print(p1.demo())

CodePudding user response:

As Python docs says:

Print objects to the text stream file, separated by sep and followed by end. sep, end, file, and flush, if present, must be given as keyword arguments.

So you can return your message in method and then just print it:

class Player:
    
     def __init__(self, name = None):
        self.name = name # creating instance variables
         
     @staticmethod
     def demo():
         return "I am a static Method"
         
p1 = Player()

print(p1.demo())
  • Related