-2

A simple example is like this:

class abs_obj:
    def __init__(self, acceptType = abs_obj):
        # do something
        pass

which gives the error message:

NameError: name 'abs_obj' is not defined

Any suggestions?

Ji Zhang
  • 128
  • 1
  • 11
  • If I try like this: acceptType = 'abs_obj', then acceptType is just a string. – Ji Zhang Oct 29 '16 at 12:22
  • This question isn't about annotations, not sure why you'd close it as a duplicate of [this one](http://stackoverflow.com/q/33533148/364696). – ShadowRanger Oct 29 '16 at 12:24
  • 1
    This sounds like an XY problem. What are you using `acceptType` for? You can just use `self.__class__` (or `type(self)`) to get a reference to the actual class of `self`. Do you need people to be able to pass a completely different class? – ShadowRanger Oct 29 '16 at 12:26
  • yes, and I need the default type is itself. – Ji Zhang Oct 29 '16 at 13:01
  • I tried both of your suggestions, however, python report a same error: NameError: name 'self' is not defined. – Ji Zhang Oct 29 '16 at 13:05
  • Again, you're probably solving the wrong problem; accepting arbitrary types like this makes no sense in 99.999% of cases. The bit I gave works inside the method without passing anything at all (if you really needed to do this, you'd accept `None` as the default and replace it with `type(self)`). What is the real problem that makes you think you need to pass a type at all? – ShadowRanger Oct 29 '16 at 14:57

1 Answers1

1

The issue here is that the class isn't actually created until after all of its methods have been compiled, but default values are calculated once at compile time.

It might be possible to specify a different default value, and change it to the desired value afterwards by manipulating the function's func_defaults attribute. But this is ugly, and not guaranteed to work in all Python implementations.

The more usual way to solve a problem like this would be:

def __init__(self, acceptType = None):
    if acceptType is None:
        acceptType = abs_obj
    # do something
    pass

If None was a valid value for the parameter, you'd have to choose some other value as the default.

jasonharper
  • 9,450
  • 2
  • 18
  • 42