【问题标题】:Python property and setter for list as for int and strings列表的 Python 属性和设置器与 int 和字符串一样
【发布时间】:2017-03-31 23:50:26
【问题描述】:

我有一个带变量的类(intstringlist)。我想使用@property 来获取变量的值,setter 来设置这个变量的值。我可以为intstring 变量实现这个概念,但不适用于list。请帮助我也为列表实施它。

class MyClass:

    def __init__(self):
        self._a = 1
        self._b = 'hello'
        self._c = [1, 2, 3]

    @property
    def a(self):
        print(self._a)

    @a.setter
    def a(self, a):
        self._a = a

    @property
    def b(self):
        print(self._b)

    @b.setter
    def b(self, b):
        self._b = b


my = MyClass()

my.a
# Output: 1
my.a = 2
my.a
# Output: 2

my.b
# Output: hello
my.b = 'world'
my.b
# Output: world


# Need to implement:
my.c
# Output: [1, 2, 3]
my.c = [4, 5, 6]
my.c
# Output: [4, 5, 6]
my.c[0] = 0
my.c
# Output: [0, 5, 6]
my.c[0]
# Output: 0

我发现了类似的问题,但它们不适合我,因为这样调用 list 的操作将不同于 int 和 string:

【问题讨论】:

  • 你能把它精简成Minimal, Complete, and Verifiable 的例子吗?这让我们更容易为您提供帮助。
  • @stephen-rauch 谢谢。我不小心从记事本中复制了两次代码。我删除了我的代码的副本。
  • 为什么你的属性打印值而不是返回它?为什么你甚至有财产?当人们说你不需要在 Python 中使用 getter 和 setter 因为 Python 有属性时,这并不意味着你应该在任何地方都使用属性。这意味着您应该使用常规属性,如果结果证明您需要附加一些逻辑来获取或设置属性,然后您会引入property

标签: python python-3.x properties


【解决方案1】:

所以我相信你的误解源于没有意识到python中的 everything 是一个对象。 liststringint 之间没有区别。请注意,在您对 intstring 的实现中,除了某些名称之外没有区别。

我已经用一个属性重铸了您的示例,然后将您的所有用例分配给它,以验证它是否适用于所有情况。

代码:

class MyClass:
    def __init__(self):
        self.my_prop = None

    @property
    def my_prop(self):
        return self._my_prop

    @my_prop.setter
    def my_prop(self, my_prop):
        self._my_prop = my_prop

测试代码:

my = MyClass()

my.my_prop = 1
assert 1 == my.my_prop
my.my_prop = 2
assert 2 == my.my_prop

my.my_prop = 'hello'
assert 'hello' == my.my_prop
my.my_prop = 'world'
assert 'world' == my.my_prop

my.my_prop = [1, 2, 3]
assert [1, 2, 3] == my.my_prop
my.my_prop = [4, 5, 6]
assert [4, 5, 6] == my.my_prop
my.my_prop[0] = 0
assert [0, 5, 6] == my.my_prop
assert 0 == my.my_prop[0]

【讨论】:

    猜你喜欢
    • 2019-06-27
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2017-01-09
    相关资源
    最近更新 更多