Python is an object-oriented (OOP) language, and it is more thorough than Java in OOP, because in Python, everything is an object, including basic data types such as int and float
In Java, to define a read-only property for a class, you only need to modify the target property with private, and then only provide getter() instead of setter(). However, Python does not have a private keyword. How to define a read-only property? There are two methods. The first one is similar to Java, and is realized by defining private properties. The second one is through \\\\\\\
Through private properties
To define a read-only property with the private property + @ property, you need to define the property name in advance, and then implement the corresponding getter method. If you don't understand the property yet.
class Vector2D(object): def __init__(self, x, y): self.__x = float(x) self.__y = float(y) @property def x(self): return self.__x @property def y(self): return self.__y if __name__ == "__main__": v = Vector2D(3, 4) print(v.x, v.y) v.x = 8 # error will be raised.
Output:
(3.0, 4.0) Traceback (most recent call last): File ...., line 16, in <module> v.x = 8 # error will be raised. AttributeError: can't set attribute
As you can see, attribute x is readable but not writable
**Through the__**
What happens when we call obj.attr=value?
Very simply, obj's zuu setattr zuu method was called. It can be verified by the following code:
class MyCls(): def __init__(self): pass def __setattr__(self, f, v): print 'setting %r = %r'%(f, v) if __name__ == '__main__': obj = MyCls() obj.new_field = 1
Output:
setting 'new_field' = 1 1
PS: no one answers the questions? Need Python learning materials? You can click the link below to get it by yourself
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76
Therefore, you only need to block the setting of attribute values in the \\\\\\\\\\
Code:
# encoding=utf8 class MyCls(object): readonly_property = 'readonly_property' def __init__(self): pass def __setattr__(self, f, v): if f == 'readonly_property': raise AttributeError('{}.{} is READ ONLY'.\ format(type(self).__name__, f)) else: self.__dict__[f] = v if __name__ == '__main__': obj = MyCls() obj.any_other_property = 'any_other_property' print(obj.any_other_property) print(obj.readonly_property) obj.readonly_property = 1
Output:
any_other_property readonly_property Traceback (most recent call last): File "...", line 21, in <module> obj.readonly_property = 1 ... AttributeError: MyCls.readonly_property is READ ONL