0

I am from the C# background.

I am trying to write getter and setters methods. In other words, I am trying to create properties for a class.

class ParamDefinition:
    def __init__(self, type_name):
        self.__type_name = type_name

    @property
    def get_type_name(self):
        return self.__type_name

    @get_type_name.setter
    def set_type_name(self, type_name):
        self.__type_name = type_name

    def printf(self):
        print(self.__type_name)

def test():
    compDef = ParamDefinition(None)

    compDef.type_name = "int"
    compDef.printf()

if __name__ == "__main__":
    test()

Output:

None

What is incorrect with my property-definition?

user366312
  • 16,949
  • 65
  • 235
  • 452
  • 2
    Does this answer your question? [What's the pythonic way to use getters and setters?](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters) – python_user Feb 19 '21 at 01:39

1 Answers1

2

Both the getter and setter need to have the same name:

class ParamDefinition:
    def __init__(self, type_name):
        self.__type_name = type_name

    @property
    def type_name(self):
        return self.__type_name

    @type_name.setter
    def type_name(self, type_name):
        self.__type_name = type_name

    def printf(self):
        print(self.__type_name)

def test():
    compDef = ParamDefinition(None)

    compDef.type_name = "int"
    compDef.printf()


if __name__ == "__main__":
    test()

Output:

int

EDIT:

While this isn't technically part of the question I thought I should add some more thoughts. You say you are from a C# background, and in C# it's fairly normal to make every field a property by default since you can add extra logic later without breaking the interface, and allows reflection.

These advantages don't really exist with Python and as you can see the boilerplate needed to turn a field into a property is much more significant than in C#. Therefore I'd recommend not using properties in Python until it's really what you need.

Turksarama
  • 1,136
  • 6
  • 13