用python简化setter吗?

时间:2018-12-28 20:34:16

标签: python

我是python的新手。我有一个User类,我只需要 init 表达式中“ self”附近的用户名。 我正在使用 add_first_name 更改名字,并使用 add_last_name 更改姓氏。为了避免重复,可以缩写一下吗?

class User:
    def __init__(self, username):
        self.username = username
        self.first_name = ""
        self.last_name = ""

    def add_first_name(self, fn)
        self.first_name = fn

    def add_last_name(self, ln)
        self.last_name = ln

对于这样的东西(伪代码):

def add_parameter(parameter, value)
     parameter = value 

为了避免重复,我在其中称呼类似:add_parameter(self.first_name =“ Jonh”)

3 个答案:

答案 0 :(得分:1)

您可以直接设置属性,而无需任何设置方法或获取方法。

class User:
    def __init__(self, username):
        self.username = username
        self.first_name = ""
        self.last_name = ""


user = User("some name")
user.first_name = "John"
user.last_name = "Smith"

答案 1 :(得分:0)

最好的方法是直接访问属性:

class User:
    def __init__(self, username):
        self.username = username
        self.first_name = ""
        self.last_name = ""


user = User("")
user.first_name = "John"
user.last_name = "Smith"

您还可以使用__getattribute____setattr__方法来控制属性的访问方式:

class User:
    def __init__(self, username):
        self.username = username
        self.first_name = ""
        self.last_name = ""
    def __setattr__(self, name, value):
        #Set attribute
    def __getattr__(self, name):
        #Get attribute

user = User("")
user.first_name = "John"
user.last_name = "Smith"

只需使用代码更改“ #Set属性”和“ #Get属性”即可设置或获取属性。

答案 2 :(得分:0)

我想我会为此戴上帽子,因为没有人提到使用@property。就像

class User:
    def __init__(self, username):
        self.username = username
        self.first_name = ""
        self.last_name = ""

    @property
    def first_name(self):
        # Here you can modify first_name however you want before you return it
        return self.first_name

    @first_name.setter
    def first_name(self, fn):
        # Here you can modify fn however you want before you set it.
        self.first_name = fn

    @property
    def last_name(self):
        # Here you can modify last_name however you want before you return it
        return self.last_name

    @last_name.setter
    def last_name(self, ln):
        # Here you can modify ln however you want before you set it.

现在您可能会认为这很冗长,您是对的!但这有两个原因。首先是在Python中,通常有getter和setter(更不用说它们永远没有地方了)。看起来很冗长的第二个原因是,它实际上比仅创建get_first_nameset_first_name更好。它允许您执行以下操作:

u = User("test_user")
u.first_name = "Test"
u.last_name = "User"
print(u.first_name)
>>> "Test"

它将自动为您调用getter和setter,而无需实际写出完整的函数调用。纯粹是语法糖吗?是的,但是由于getter和setter在Python中不是标准的,因此它还可以帮助其他人更轻松地遵循您的代码。