mike01010
mike01010

Reputation: 6038

implement default class instance method

i have the following class which i use when declaring 'constants' to map one value to another. Is there away in python implement a default method such that anytime an instance of this class referenced without a specific method, a default method is executed?

class FieldMap:
    def __init__(self, old_field, new_field):
        self._fld_map = (old_field, new_field)

    def old_fld(self):
        return self._fld_map[0]

    def new_fld(self):
        return self._fld_map[1]

SEC_ID = FieldMap('value','price')
SEC_NAME = FieldMap('entity_name', 'security_name')
SEC_TICKER = FieldMap('entity_attr', 'ticker')

#Edit: updating example to provide a real example of what i want to achieve
dict = {}
dict['price'] = 1234
print dict[SEC_ID]  <--would like this to print out the value 1234 because ideally, the default method would call new_fld() and return 'price'

Upvotes: 0

Views: 58

Answers (2)

Platinum Azure
Platinum Azure

Reputation: 46183

There's no way to implement an automatic method call in all cases, but it is possible to hook into certain method calls. In the case of print, Python will attempt to call a __str__ method on the instance if one exists. So you could do something like this:

class FieldMap:
    def __init__(self, old_field, new_field):
        self._fld_map = (old_field, new_field)

    def old_fld(self):
        return self._fld_map[0]

    def new_fld(self):
        return self._fld_map[1]

    def __str__(self):
        return self.new_fld()

Upvotes: 1

chepner
chepner

Reputation: 530882

It doesn't call a default method, but it sounds like you just want to override __str__:

def __str__(self):
    return self._fld_map[1]

Note that this is just the definition of new_fld, so you could simply add the following to your class:

__str__ = new_fld

Upvotes: 1

Related Questions