1

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

public class ClassName 
{
    public ClassName { }

    public string Val { get; set; }

    ...
}

ClassName cn = new ClassName();

cn.Val = "Hi StackOverflow!!";

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

4

3 回答 3

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")
于 2011-07-30T11:37:17.693 回答
2

在这个意义上,Python 没有 getter 和 setter。下面的代码等价于上面的代码:

class ClassName:
    pass

cn = ClassName()

cn.val = "Hi StackOverflow!!"

请注意,python 没有提到 getter/setter;你甚至不需要声明val,直到你设置它。要制作自定义 getter/setter,您可以执行以下操作:

class ClassName:
    _val = "" # members preceded with an underscore are considered private, although this isn't enforced by the interpreter

    def set_val(self, new_val):
        self._val = new_val

    def get_val(self):
        return self._val
于 2011-07-30T11:31:20.873 回答
0
class a:
 pass    //you need not to declare val
x=a();
x.val="hi all";
于 2011-07-30T11:29:33.597 回答