Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get attributes in the order they are declared in a Python class?

As described in PEP435, an enum can be defined this way:

class Color(Enum):
    red = 1
    green = 2
    blue = 3

And the resulting enum members of Color can be iterated in definition order: Color.red, Color.green, Color.blue.

This reminds me of Form in Django, in which fields can be rendered in the order they are declared in a Form subclass. They implemented this by maintaining a field counter, every time a new field is instantiated the counter value get incremented.

But in the definition of Color, we don't have something like a FormField, how can we implement this?

like image 752
satoru Avatar asked May 13 '13 03:05

satoru


People also ask

Does the order of methods in a class matter Python?

It doesn't matter in which order variables and functions are defined in Class in Python.

How do you get all the attributes of an object?

Use the dir() function to get all attributes of an object, e.g. print(dir(object)) . The dir function will return a list of the valid attributes of the provided object. Copied! The dir function takes an object and returns a list containing the object's attributes.

What is __ Getattr __ in Python?

Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned.


1 Answers

In Python 3, you can customize the namespace that a class is declared in with the metaclass. For example, you can use an OrderedDict:

from collections import OrderedDict

class EnumMeta(type):

    def __new__(mcls, cls, bases, d):
        print(d)
        return type.__new__(mcls, cls, bases, d)

    @classmethod
    def __prepare__(mcls, cls, bases):
        return OrderedDict()


class Color(metaclass=EnumMeta):
    red = 1
    green = 2
    blue = 3

This prints

OrderedDict([('__module__', '__main__'), ('red', 1), ('green', 2), ('blue', 3)])
like image 100
Benjamin Peterson Avatar answered Oct 05 '22 23:10

Benjamin Peterson