What is considered an "advanced" topic in Python?
Ethan Furman
ethan at stoneleaf.us
Fri May 29 17:39:44 EDT 2015
On 05/29/2015 02:06 PM, sohcahtoa82 at gmail.com wrote:
> On Friday, May 29, 2015 at 10:18:29 AM UTC-7, Ethan Furman wrote:
>>
>> 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.
Hence the need for a metaclass, as the point is to operate on the class, not the instance.
> 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?
Yes. In the case of Enum, however, it takes any user-defined __new__, which is needed for creating the original instances, and replaces it with a __new__ that only returns the already defined ones.
--
~Ethan~
More information about the Python-list
mailing list