简体   繁体   English

我可以在 python 中定义 setter 吗?

[英]Can I define setters in python?

I want to create a class in python that has setters for its attributes.我想在 python 中创建一个具有属性设置器的类。

For example suppose we have a class named myClass and it has x attribute.例如,假设我们有一个名为myClass的类,它有x属性。 I want to create it so that when someone changes x value, only two last digits of x (x % 100) are saved.我想创建它,以便当有人更改 x 值时,只保存 x (x % 100)最后两位数字。

using myClass in python shell:在 python shell 中使用 myClass:

>>> obj = myClass()
>>> obj.x = 352562
>>> obj.x
62

Can I define a setter that is called automatically when changing the value of x ?我可以定义一个在更改x值时自动调用的 setter 吗?

You can use properties decorators您可以使用属性装饰器

@property
def x(self):
    return self._x

@x.setter
def x(self, value):
    self._x = value % 100

Also you will have to declare and initialise _x in your init method for a safer code此外,您必须在init方法中声明和初始化 _x 以获得更安全的代码

See this stack overflow post for more information有关更多信息,请参阅此堆栈溢出帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM