弃用python中类的属性

Ish*_*ema -3 python deprecated deprecation-warning

我正在尝试弃用类的属性。

class A:
   def __init__(self,
   variable1: int,
   ##to be deprecated
   variable2: int )
   {....}
Run Code Online (Sandbox Code Playgroud)

预期行为:如果用户尝试使用变量 2,他应该收到警告,指出它已被弃用。

Tgs*_*591 6

你可以给它一个None默认值并确保它没有设置:

import warnings

class A:
    def __init__(
        self,
        variable1,
        variable2=None,
    ):

        if variable2 is not None:
            warnings.warn(
                "variable2 is deprecated", DeprecationWarning
            )
Run Code Online (Sandbox Code Playgroud)

与 kwargs 一起使用:

>>> A(1, variable2=123)
<ipython-input-4-e722737121fe>:12: DeprecationWarning: variable2 is deprecated
Run Code Online (Sandbox Code Playgroud)

适用于位置参数:

>>> A(1, 123)
<ipython-input-4-e722737121fe>:12: DeprecationWarning: variable2 is deprecated
Run Code Online (Sandbox Code Playgroud)


Dan*_*ker 5

您可以将variable2其作为属性来实现。

import warnings

class A:
    def __init__(self, variable1: int, variable2: int):
        self.variable1 = variable1
        self._variable2 = variable2

    @property
    def variable2(self):
        warnings.warn('The use of variable2 is deprecated.', DeprecationWarning)
        return self._variable2

    @variable2.setter
    def variable2(self, value: int):
        warnings.warn('The use of variable2 is deprecated.', DeprecationWarning)
        self._variable2 = value
Run Code Online (Sandbox Code Playgroud)