1

In Python I defined a class:

class Myclass(BaseModule):

I would like print argument BaseModule.

Something like this:

class Myclass(BaseModule):
     logger.info("Argument=%s" % BaseModule.get_name())

Doesn't work:

unbound method get_name() must be called with BaseModule instance as 
first argument (got nothing instead)
martineau
  • 119,623
  • 25
  • 170
  • 301
azef
  • 13
  • 1
  • 4

4 Answers4

7

You can access the name of the class with:

BaseModule.__name__
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • +1 for helping show the OP the more Pythonic way of doing things, rather than just bashing in a solution for them. I was going to start suggesting a `@classmethod`, but a automagically defined variable is even better. – dwanderson Jan 06 '16 at 14:08
3

First, you can find your answer here : solution source

    >>> class Base(object):
...     pass
...
>>> class Derived(Base):
...     def print_base(self):
...         for base in self.__class__.__bases__:
...             print base.__name__
...
>>> foo = Derived()
>>> foo.print_base()
Base
Community
  • 1
  • 1
Idan Azuri
  • 623
  • 4
  • 17
1

If you want to call a superclass method, you can use super(). But this will need you to have an instance, which you won't if you put your logging code there.

class Base(object):
    def get_name(self):
        return "Base name"

class Derived(Base):
    def __init__(self):
        print super(Derived, self).get_name()

Derived() # prints 'Base name'
Vlad
  • 18,195
  • 4
  • 41
  • 71
0

Just like the error says, you need to instantiate (create an instance of) BaseModule first.

class MyClass(BaseModule):
    def __init__(self):
        base_mod = BaseModule()
        logger.info("Argument=%s", base_mod.get_name())

And it's not an argument, it's a parent class that MyClass inherits from. Argument is, for example, self from __init__. It's important to know the correct terminology to avoid confusion later.

makos
  • 157
  • 3
  • 14