公共字符串blaBla{获取;设置;}
本文关键字:设置 获取 字符串 blaBla | 更新日期: 2023-09-27 18:03:55
考虑下面的例子来更好地理解我的问题:
public class ClassName
{
public ClassName { }
public string Val { get; set; }
...
}
ClassName cn = new ClassName();
cn.Val = "Hi StackOverflow!!";
这段代码在python中等价于什么?
您可以轻松地向任何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")
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
class a:
pass //you need not to declare val
x=a();
x.val="hi all";