0

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'

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, that works for print. it doesn't work for say something like this though mydict[SEC_ID] = 1234. i know that isn't exactly what i asked, maybe i will update the question
In that case, you need to either call str(SEC_ID) or store elements using dict[SEC_ID] = 1234 and then dict[SEC_ID] to retrieve. In general, you can't expect Python to magically convert types-- how would it know to convert to string or integer in most cases?
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.