公共字符串blaBla { 获取;放; 在蟒蛇

Sha*_*kan 1 c# python methods class equivalent

考虑以下示例以更好地理解我的问题:

public class ClassName 
{
    public ClassName { }

    public string Val { get; set; }

    ...
}

ClassName cn = new ClassName();

cn.Val = "Hi StackOverflow!!";
Run Code Online (Sandbox Code Playgroud)

python中这段代码的等价物是什么?

rob*_*ert 6

您可以轻松地将成员添加到任何 Python 对象,如其他答案中所示。对于像 C# 中更复杂的 get/set 方法,请参阅内置属性

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")
Run Code Online (Sandbox Code Playgroud)