简体   繁体   English

为 python 分配不同的值 object

[英]assign different value to python object

I want to make a python class named "Foo" that has an attribute called "x" which is an int with a default value of 0. If I assign a posetive value to x it would automatically change to 10 and if I assign a negative value it would change it to -10.我想制作一个名为“Foo”的 python class,它有一个名为“x”的属性,它是一个默认值为 0 的 int。如果我为 x 分配一个正值,它会自动更改为 10,如果我分配一个负值值它将更改为-10。 for example:例如:

>>p = Foo()
>>print(p.x)
0
>>p.x = -45
>>print(p.x)
-10
>>p.x = 85
>>print(p.x)
10

Utilize the property decorator:使用property装饰器:

You first define _x as a class member in the constructor:您首先在构造函数中将_x定义为 class 成员:

    def __init__(self):
        self._x = 0

and initialize it with 0 .并用0初始化它。

Then you define x as property:然后将x定义为属性:

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

This means that we can get the values of _x through the name x .这意味着我们可以通过名称x获取_x的值。

Then you define setter for x with @x.setter :然后使用@x.setterx定义 setter:

    @x.setter
    def x(self, value):
        self._x = 10 if value > 0 else (-10 if value < 0 else 0)

This overrides the original logics for setting value to x , with the one that you defined.这将使用您定义的值覆盖将 value 设置为x的原始逻辑。

ATTENTION: _x is still accessible, and if you change it the magic defined above won't hold (there is no private class members such as in other languages like C, C++, C#, Java, etc...).注意: _x仍然可以访问,如果您更改它,上面定义的魔法将不成立(没有private class 成员,例如其他语言中的 C、C++、C#、Java 等)。 Things that start with _ conventionally means that they are of internal use._开头的东西通常意味着它们是内部使用的。

Code:代码:

class Foo(object):
    def __init__(self):
        self._x = 0

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

    @x.setter
    def x(self, value):
        self._x = 10 if value > 0 else (-10 if value < 0 else 0)

p = Foo()
# 0
print(p.x)

p.x = -45
# -10
print(p.x)

p.x = 85
# 10
print(p.x)

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

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