Wondercricket Wondercricket - 1 year ago 60
Python Question

Is there any reason for giving self a default value?

I was browsing through some code, and I noticed a line that caught my attention. The code is similar to the example below

class MyClass:
def __init__(self):

def call_me(self=''):

This looks like any other class that I have seen, however a
is being passed in as default value for

If I print out
, it behaves as normal

>> <__main__.MyClass object at 0x000002A12E7CA908>

This has been bugging me and I cannot figure out why this would be used. Is there any reason to why a
would be passed in as a default value for

Jim Jim
Answer Source

Not really, it's just an odd way of making it available to call via the class, too:


works fine since, even though nothing is implicitly passed as with instances, the default value for that argument is provided. If no default was provided, when called, this would of course raise the TypeError we all love.

Bottom line, this is more confusing than it is practical. If you need to do something similar I'd advice a simple staticmethod (or classmethod if you need to access class attributes) with a default argument to achieve a similar effect.

That way you don't stump anyone reading your code (like the developer who wrote this did with you ;-):

def call_me(a=''):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download