【问题标题】:public string blaBla { get; set; } in python公共字符串 blaBla { 获取;放; } 在蟒蛇
【发布时间】:2011-07-30 11:23:08
【问题描述】:

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

public class ClassName 
{
    public ClassName { }

    public string Val { get; set; }

    ...
}

ClassName cn = new ClassName();

cn.Val = "Hi StackOverflow!!";

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

【问题讨论】:

    标签: c# python class methods equivalent


    【解决方案1】:

    您可以轻松地将成员添加到任何 Python 对象,如其他答案所示。有关 C# 等更复杂的 get/set 方法,请参阅 property 内置函数:

    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")
    

    【讨论】:

      【解决方案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
      

      【讨论】:

      【解决方案3】:
      class a:
       pass    //you need not to declare val
      x=a();
      x.val="hi all";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-22
        • 1970-01-01
        • 1970-01-01
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-22
        相关资源
        最近更新 更多