class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
#Python2
class MyClass(BaseClass):
__metaclass__ = Singleton
#Python3
class MyClass(BaseClass, metaclass=Singleton):
pass
Python can we dynamically define new fields to a class during runtime.
It's possible to restrict the instance attributes that can be added through the class attribute __slots__
:
>>> class B(object):
... __slots__ = ['only_one_attribute']
... def __init__(self):
... self.only_one_attribute = 'one'
... def add_attr(self):
... self.another_attribute = 'two'
- 注意: B的派生类也必须 显式 定义
__slots__
, 即便 是空的__slots__ = {}
class A(object):
def __delattr__(self, key) :
raise Exception( "can not delete "+key )
def __setitem__(self,key, value) :
...
def __getitem__(self,key) :
...
- using a setter method to copy content value
>>> class A(object):
... def __init__(self, a):
... self._a = a
...
... @property
... def a(self):
... return self._a
...
>>> a = A('test')
>>> a.a
'test'
>>> a.a = 'pleh'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
- more simple way ...
- https://github.com/oz123/oz123.github.com/blob/master/media/uploads/readonly_properties.py
- this
readonly_properties
is for python3 , if you use python2.7, you may need modify some code
...
class NewClass(cls , object ):
...
super( NewClass, self ).__setattr__(name, value)