Skip to content

Latest commit

 

History

History
120 lines (87 loc) · 2.83 KB

python_oop.md

File metadata and controls

120 lines (87 loc) · 2.83 KB

oop for python

Singleton

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

disable dynamically define new fields to a class

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__ = {}

disable dynamically del a field from a class

class A(object):
    def __delattr__(self, key) :         
        raise Exception( "can not delete "+key )

access like a dict

def __setitem__(self,key, value) :
    ...
def __getitem__(self,key) :
    ...

assignment lick c struct

  • using a setter method to copy content value

readonly class field

>>> 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
...
class NewClass(cls , object ):
    ...
        super( NewClass, self  ).__setattr__(name, value)