Ross
Ross

Reputation: 46987

Access child class instance in parent

In Python I have a dictionary of settings which relate to a task class. In the parent constructor of these tasks I would like to store only the relevant settings, but to do this I need to access the child class from the parent class.

settings = {
    SomeTask: { 'foo': 'bar' },
    SomeOtherTask: { 'bar': 'foo' },
}

class SomeTask(BaseTask):
    pass

class SomeOtherTask(BaseTask):
    pass

class BaseTask:
    def __init__(self, settings):
        self.settings = settings[child_class]

In PHP I can do this by calling get_class($this); in the constructor (returns the child class name rather than the parent), does Python have something similar?

Upvotes: 3

Views: 7392

Answers (3)

glglgl
glglgl

Reputation: 91017

I would it consider much cleaner to do

class SomeTask(BaseTask):
    settings = { 'foo': 'bar' }

class SomeOtherTask(BaseTask):
    settings = { 'bar': 'foo' }

provided no changes are made to these settings.

This way, the changes are tightly coupled to the class and there is only one dict object containing these settings.

Upvotes: 0

Aya
Aya

Reputation: 41950

The closest Python equivalent to the PHP code...

$class_name = get_class($my_object)

...is...

class_name = my_object.__class__.__name__

...which should work for both old-style and new-style Python classes.

Indeed, if you index the classes by their name, rather than using a reference to the class object, then you don't need to pass in the settings parameter (which I assume you only did to avoid a circular reference), and access the global settings variable directly...

settings = {
    'SomeTask': { 'foo': 'bar' },
    'SomeOtherTask': { 'bar': 'foo' },
}

class BaseTask:
    def __init__(self):
        self.settings = settings[self.__class__.__name__]

class SomeTask(BaseTask):
    pass

class SomeOtherTask(BaseTask):
    pass

Upvotes: 1

Matti John
Matti John

Reputation: 20477

Just do this:

class BaseTask:
    def __init__(self, settings):
        self.settings = settings[self.__class__]

class SomeTask(BaseTask):
    pass

class SomeOtherTask(BaseTask):
    pass

When you initialise one of the child classes with the settings, they will do what you expect.

Upvotes: 3

Related Questions