Is it possible to create a method in a class that can be called on an attribute?
For example how all Str types have an upper() method that can be called on it.
class MyClass():
attribute_a = "foo"
attribute_b = "bar"
# no problem, but locked to only adds period to attribute_a as it is being explicitly named
def add_period(self):
return self.attribute_a + "."
# wish to have a method that can be called on the attribute itself
def add_period_method(self):
# ???
pass
cls = MyClass()
print(cls.add_period()) # no problem
print(cls.attribute_a.add_period_method()) # no chance
>Solution :
Sure, you can just make another class:
class WithPeriod(str):
def add_period(self):
return self + "."
class MyClass():
attribute_a = WithPeriod("foo")
attribute_b = WithPeriod("bar")
Example usage:
>>> instance = MyClass()
>>> instance.attribute_a
'foo'
>>> instance.attribute_a.add_period()
'foo.'