[Python-Dev] PEP 435 -- Adding an Enum type to the Python standard library (original) (raw)

Larry Hastings larry at hastings.org
Fri Apr 26 19:30:40 CEST 2013


On 04/26/2013 09:27 AM, Serhiy Storchaka wrote:

26.04.13 18:50, Larry Hastings написав(ла):

The standard Java documentation on enums:

http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html This example requires more than features discussed here. It requires an enum constructor. class Planet(Enum): MERCURY = Planet(3.303e+23, 2.4397e6) [...] This can't work because the name Planet in the class definition is not defined.

It can't work because you inserted the word "Planet" there. If you omit the word "Planet", this would work fine with something like the metaclass instantiate-all-data-members behavior in flufl.enum 4.

Here is the hack, demonstrated in Python 3:

class Metaclass(type):
     def __new__(cls, name, bases, namespace):
         result = type.__new__(cls, name, bases, dict(namespace))
         for name, value in namespace.items():
             if not (callable(value) or name.startswith("__")):
                 value = result(name, value)
                 setattr(result, name, value)
         return result

class Planet(metaclass=Metaclass):
     MERCURY = (3.303e+23, 2.4397e6)

     def __init__(self, name, value):
         self.mass, self.radius = value

     def surfaceGravity(self):
         return 6.67300E-11 * self.mass / (self.radius ** 2)

     def surfaceWeight(self, otherMass):
         return otherMass * self.surfaceGravity()


print("If you weigh 175 pounds, on Mercury you'd weigh",
Planet.MERCURY.surfaceWeight(175))

//arry/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20130426/a610d639/attachment.html>



More information about the Python-Dev mailing list