Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling a method on a class attribute in Python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading