In Python, when should I use the meta class?

I went through this: What is a metaclass in Python?

But can anyone explain more specifically when to use the concept of a metaclass and when it is very convenient?

Suppose I have a class as shown below:

 class Book(object):
    CATEGORIES = ['programming','literature','physics']
    def _get_book_name(self,book):
        return book['title']
    def _get_category(self, book):
        for cat in self.CATEGORIES:
            if book['title'].find(cat) > -1:
                return cat  
        return "Other"


if __name__ == '__main__':
    b = Book()
    dummy_book = {'title':'Python Guide of Programming', 'status':'available'}
    print b._get_category(dummy_book)

For this class.

In what situation should I use the meta class and why is it useful?

Thanks in advance.

+5
source share
5 answers

check out the Meta Class Made Easy link to find out how and when to use the metaclass.

-1
source

, . - , , , . 600Kloc 7 : ABCMeta , 4x models.SubfieldBase Django , Django. @Ignacio, , ( ), .

+8

, ( ). . , . , , .

- , ; , . type , , , :

  • , , MRO
  • MyClass(*args, **kwargs) i = MyClass.__new__(MyClass, *args, **kwargs), , i.__init__(*args, **kwargs),
  • , , ,
  • Etc

, , - , , type. type, , , ; , , - (, , ) Book, .

, - , , , . , " , " - ; , .

google , , , ; . . , . factory , , , , , , .

, , Python - , .

- "singleton pattern", , ; , . ( , , , , ). , __new__ __init__. , , Python __new__, __init__ , , - singleton. , Python , , , , , Python , , , , ?

class Singleton(type):
    def __init__(self, *args, **kwargs):
        super(Singleton, self).__init__(*args, **kwargs)
        self.__instance = None

    def __call__(self, *args, **kwargs):
        if self.__instance is None:
            self.__instance = super(Singleton, self).__call__(*args, **kwargs)
        return self.__instance

10 , , __metaclass__ = Singleton, .. , , . , - .

Book , -, . , , -, ( "man, , , , ?" ). , - , , Python; , Singleton, .

+3

, , .

, dict. , .

, :

  • __ call__,
  • __ getattribute__,
  • __ setattr__,
  • __ repr__, , diplayed

, , , , .

+3

If for any reason you want to do things like Class[x], x in Classetc., you need to use metaclasses:

class Meta(type):
    def __getitem__(cls, x):
        return x ** 2

    def __contains__(cls, x):
        return int(x ** (0.5)) == x ** 0.5

# Python 2.x
class Class(object):
    __metaclass__ = Meta

# Python 3.x
class Class(metaclass=Meta):
    pass

print Class[2]
print 4 in Class
+1
source

All Articles