What is considered an "advanced" topic in Python?

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Fri May 29 17:06:15 EDT 2015


On Friday, May 29, 2015 at 10:18:29 AM UTC-7, Ethan Furman wrote:
> On 05/29/2015 10:03 AM, sohcahtoa82 at gmail.com wrote:
> > On Friday, May 29, 2015 at 9:02:06 AM UTC-7, Mike Driscoll wrote:
> 
> >> I've been asked on several occasions to write about intermediate or advanced topics
> >>  in Python and I was wondering what the community considers to be "intermediate" or
> >>  "advanced". I realize we're all growing in our abilities with the language, so this
> >>  is going to be very subjective, but I am still curious what my fellow Python
> >>  developers think about this topic.
> >
> > Metaclasses.
> >
> > I've read about them.  I still don't understand them, why you would want them, and what you gain from them.
> 
> Metaclasses change the way a class behaves.
> 
> For example, the new (in 3.4) Enum class uses a metaclass.
> 
>    class SomeEnum(Enum):
>       first = 1
>       second = 2
>       third = 3
> 
> The metaclass changes normal class behavior to:
> 
>    - support iterating: list(SomeEnum) --> [SomeEnum.first, SomeEnum.second, SomeEnum.third]
>    - support a length:  len(SomeEnum) --> 3
>    - not allow new instances to be created:  --> SomeEnum(1) is SomeEnum(1)  # True
> 
> --
> ~Ethan~

Regarding the first two, you can implement __iter__ and __len__ functions to create that functionality, though those functions would operate on an instance of the class, not the class itself.

As for the third, can't you override the __new__ function to make attempts to create a new instance just return a previously created instance?



More information about the Python-list mailing list