如何在 python 的方法中使用属性函数?

我尝试编写代码 2 来做与代码 1 相同的事情。但是,代码 2 不起作用。为什么?如何在 python 的方法中使用属性函数?


(代码 1)


class Spam:

    def __init__(self, is_less_sodium):

        self.__is_less_sodium = is_less_sodium


    def __getter(self):

        return self.__is_less_sodium


    is_less_sodium = property(__getter)


my_spam = Spam(False)

print(my_spam.is_less_sodium)


########## Result ##########

# False

(代码 2)


class Spam:

    def __init__(self, is_less_sodium):

        self.__is_less_sodium = is_less_sodium

        Spam.is_less_sodium = property(self.__getter)


    def __getter(self):

        return self.__is_less_sodium


my_spam = Spam(False)

print(my_spam.is_less_sodium)


########## Result ##########

# Traceback (most recent call last):

#   File "code2.py", line 10, in <module>

#     print(my_spam.is_less_sodium)

# TypeError: __getter() takes 1 positional argument but 2 were given

我理解代码1中的返回值property(__getter)是赋值给的is_less_sodium,这是一个类变量Spam。但是,这种理解似乎是错误的。


守候你守候我
浏览 100回答 1
1回答

慕尼黑的夜晚无繁华

class Spam:&nbsp; &nbsp; def __init__(self, is_less_sodium):&nbsp; &nbsp; &nbsp; &nbsp; self.__is_less_sodium = is_less_sodium&nbsp; &nbsp; &nbsp; &nbsp; Spam.is_less_sodium = property(Spam.__getter,)&nbsp; &nbsp; def __getter(self):&nbsp; &nbsp; &nbsp; &nbsp; return self.__is_less_sodiummy_spam = Spam(False)print(my_spam.is_less_sodium)您可以使用该语法,但您还必须从类级别引用该函数,而不是实例函数。装饰器语法更简洁。class Spam:&nbsp; &nbsp; def __init__(self, is_less_sodium):&nbsp; &nbsp; &nbsp; &nbsp; self.__is_less_sodium = is_less_sodium&nbsp; &nbsp; @property&nbsp; &nbsp; def is_less_sodium(self):&nbsp; &nbsp; &nbsp; &nbsp; return self.__is_less_sodium&nbsp; &nbsp; @is_less_sodium.setter&nbsp; &nbsp; def set_is_less_sodium(self):&nbsp; &nbsp; &nbsp; &nbsp; self.__is_less_sodiummy_spam = Spam(False)print(my_spam.is_less_sodium)my_spam.is_less_sodium = Trueprint(my_spam.is_less_sodium)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python