Search code examples
c#pythonclassmethodsequivalent

public string blaBla { get; set; } in python


Consider the following example to understand better my question:

public class ClassName 
{
    public ClassName { }

    public string Val { get; set; }

    ...
}

ClassName cn = new ClassName();

cn.Val = "Hi StackOverflow!!";

What would be the equivalent of this code in python?


Solution

  • You can easily add members to any Python object as show in other answers. For more complicated get/set methods like in C#, see the property builtin:

    class Foo(object):
       def __init__(self):
          self._x = 0
    
       def _get_x(self):
          return self._x
    
       def _set_x(self, x):
          self._x = x
    
       def _del_x(self):
          del self._x
    
       x = property(_get_x, _set_x, _del_x, "the x property")