What are some (concrete) use-cases for metaclasses?

前端 未结 19 1124
悲&欢浪女
悲&欢浪女 2020-12-07 06:51

I have a friend who likes to use metaclasses, and regularly offers them as a solution.

I am of the mind that you almost never need to use metaclasses. Why? because I

19条回答
  •  不知归路
    2020-12-07 07:30

    The only time I used metaclasses in Python was when writing a wrapper for the Flickr API.

    My goal was to scrape flickr's api site and dynamically generate a complete class hierarchy to allow API access using Python objects:

    # Both the photo type and the flickr.photos.search API method 
    # are generated at "run-time"
    for photo in flickr.photos.search(text=balloons):
        print photo.description
    

    So in that example, because I generated the entire Python Flickr API from the website, I really don't know the class definitions at runtime. Being able to dynamically generate types was very useful.

提交回复
热议问题