简体   繁体   English

实现默认的类实例方法

[英]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? python中是否有实现默认方法的方法,以便在没有特定方法的情况下引用此类的实例时,都将执行默认方法?

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'

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. 对于print ,Python将尝试在实例上调用__str__方法(如果存在)。 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()

It doesn't call a default method, but it sounds like you just want to override __str__ : 它没有调用默认方法,但是听起来您只想覆盖__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: 请注意,这只是new_fld的定义,因此您可以在类中添加以下内容:

__str__ = new_fld

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM