azef
azef

Reputation: 13

Get base class' name?

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)

Upvotes: 1

Views: 5558

Answers (4)

Idan Azuri
Idan Azuri

Reputation: 721

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

Upvotes: 3

Mike Müller
Mike Müller

Reputation: 85462

You can access the name of the class with:

BaseModule.__name__

Upvotes: 7

makos
makos

Reputation: 157

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.

Upvotes: 0

Vlad
Vlad

Reputation: 18633

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'

Upvotes: 1

Related Questions