公共字符串 blaBla { 得到;放;在Python中

发布于 2024-11-27 05:54:54 字数 243 浏览 1 评论 0原文

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

public class ClassName 
{
    public ClassName { }

    public string Val { get; set; }

    ...
}

ClassName cn = new ClassName();

cn.Val = "Hi StackOverflow!!";

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

‘画卷フ 2024-12-04 05:54:54

您可以轻松地将成员添加到任何 Python 对象,如其他答案中所示。对于更复杂的 get/set 方法(如 C# 中的方法),请参阅内置的 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")

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")
以往的大感动 2024-12-04 05:54:54

从这个意义上来说,Python 没有 getter 和 setter。以下代码与上面的代码等效:

class ClassName:
    pass

cn = ClassName()

cn.val = "Hi StackOverflow!!"

请注意,python 没有提及 getters/setters;在设置之前,您甚至不需要声明 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

Python does not have getters and setters in this sense. The following code is the equivalent to the above code:

class ClassName:
    pass

cn = ClassName()

cn.val = "Hi StackOverflow!!"

Notice that python has no mention of getters/setters; you don't even need to declare val until you set it. To make custom getters/setters you could do for example this:

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
花间憩 2024-12-04 05:54:54
class a:
 pass    //you need not to declare val
x=a();
x.val="hi all";
class a:
 pass    //you need not to declare val
x=a();
x.val="hi all";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文