如何防止在 class 之外重新分配 class 方法?
How to prevent re-assignment of a class method outside the class?
我希望我的某些 class 方法不能在 class 的外部(或外部和内部)重新分配。 A
的函数在python中也是对象,是否可以实现我想要的?这是方法;
def x(self):
"""Return x, the horizontal distance between the shape and the leftmost
of the screen, in pixels.
"""
return self.__x
现在在class之外,很容易搞砸这个方法;
shape = Shape(10, 20)
shape.x = 30
print(shape.x) # Prints 30
print(shape.x()) # TypeError: 'int' object is not callable
是否可以防止这种 class 方法的赋值?
使 x
成为 属性 而没有 setter,而不是方法。
class Shape:
...
@property
def x(self):
return self.__x
尝试分配给 x
将导致异常:
>>> shape.x = 30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
如果您确实想要必须调用的东西,请使用 属性 return 代替函数将要调用的值 return.
class Shape:
@property
def x(self):
return lambda: self.__x
例如,您可以覆盖 __setattr__
方法来检查密钥是否在禁止列表中...
class Shape:
def __init__(self, a, b):
self.__x = a
self.__y = b
def x(self):
return self.__x
def __setattr__(self, key, value):
if key in ('x', 'y'):
raise TypeError(f"You can't change {key}")
super(Shape, self).__setattr__(key, value)
shape = Shape(11, 20)
shape.z = 100 # OK
print(shape.z)
print(shape.x())
shape.x = 30 # raise an exception
注意:正如@Chepner 指出的那样,重写 __setattr__
只是阻止您通过赋值语句更改 x
的值,而不是更改它根本。喜欢 object.__setattr__(shape, 'x', 30)
我希望我的某些 class 方法不能在 class 的外部(或外部和内部)重新分配。 A
的函数在python中也是对象,是否可以实现我想要的?这是方法;
def x(self):
"""Return x, the horizontal distance between the shape and the leftmost
of the screen, in pixels.
"""
return self.__x
现在在class之外,很容易搞砸这个方法;
shape = Shape(10, 20)
shape.x = 30
print(shape.x) # Prints 30
print(shape.x()) # TypeError: 'int' object is not callable
是否可以防止这种 class 方法的赋值?
使 x
成为 属性 而没有 setter,而不是方法。
class Shape:
...
@property
def x(self):
return self.__x
尝试分配给 x
将导致异常:
>>> shape.x = 30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
如果您确实想要必须调用的东西,请使用 属性 return 代替函数将要调用的值 return.
class Shape:
@property
def x(self):
return lambda: self.__x
例如,您可以覆盖 __setattr__
方法来检查密钥是否在禁止列表中...
class Shape:
def __init__(self, a, b):
self.__x = a
self.__y = b
def x(self):
return self.__x
def __setattr__(self, key, value):
if key in ('x', 'y'):
raise TypeError(f"You can't change {key}")
super(Shape, self).__setattr__(key, value)
shape = Shape(11, 20)
shape.z = 100 # OK
print(shape.z)
print(shape.x())
shape.x = 30 # raise an exception
注意:正如@Chepner 指出的那样,重写 __setattr__
只是阻止您通过赋值语句更改 x
的值,而不是更改它根本。喜欢 object.__setattr__(shape, 'x', 30)