C# 的自定义属性设置器的 Python 替代方案是什么?

问题描述 投票:0回答:2

我将从 C# 世界转向 Python。在 C# 中,我可以使用

get
set
在为属性设置值时更新其他对象属性,如下所示:

private int _age;
private string _description;

public int Age
{
    set
    {
        _age = value;
        _description = (_age < 1500) ? "new": "old";
    }
}

在Python中,我有以下类定义:

class Record(object):
    age = 0
    description = ""
    <...a bunch of other properties...>

如何在设置

description
属性时设置
Record
对象的
age
属性,就像在 C# 中一样,而无需编写
get_age(self):
等自定义函数和
set_age(self):

python oop setter
2个回答
-1
投票

一种 Pythonic 方法是使用属性装饰器,它创建一个类似于属性的方法:

class Record:
    def __init__(self, age):
        self.age = age
    
    @property
    def description(self):
        return "new" if self.age < 1500 else "old"
    
print(Record(age = 1600).description) # old

通过这种方法,

description
不会存储在内存中,而是在每次访问时重新计算。

另一种方法是使用全套 getter 和 setter 装饰器,但它需要创建您想要避免的其他方法:

class Record:
    def __init__(self, age):
        self.description = None
        self.age = age
    
    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        self.description = "new" if value < 1500 else "old"
        self._age = value
    
print(Record(age = 1600).description)

这样

description
就存储在对象中,并且每次将值设置为
self.age
时都会更新。


-2
投票

装饰器让您可以在类中使用 setter 和 getter

class Record:
    def __init__(self, age):
        self.age = age
        self.description = age

    # using property decorator
    # a getter function
    @property
    def description(self):
        print("getter method called")
        return self._description
    
    # a setter function
    @description.setter
    def description(self, age):
        if(age < 1500):
            self._description = "new"
        else:
            self._description = "old"
© www.soinside.com 2019 - 2024. All rights reserved.