Explain the concept of metaclasses in Python and provide an example of how they can be used.
Metaclasses in Python allow you to customize class creation. They are like class factories. Here's an example of a metaclass:
class Meta(type):
def __new__(cls, name, bases, attrs):
uppercase_attrs = {}
for attr, value in attrs.items():
if not attr.startswith('__'):
uppercase_attrs[attr.upper()] = value
else:
uppercase_attrs[attr] = value
return super(Meta, cls).__new__(cls, name, bases, uppercase_attrs)
class MyClass(metaclass=Meta):
x = 10
# Usage
obj = MyClass()
print(obj.X) # Output: 10
In this example, the metaclass Meta changes all attribute names to uppercase when creating the MyClass class.