r/learnpython • ¯\_(ツ)_/¯ • Feb 13 '21

HOW HAVE I BEEN SO BLIND!!!!

IT IS ALL OBJECT....

EVERYTHING IS OBEJCT!!!!

EVERYTHING!!!!!

OH MY GOD!!!!

IT'S ALL OBJECT!!!!!!

AHHHHH!!!!

1.3k Upvotes

200 comments sorted by

View all comments

Show parent comments

57

u/[deleted] Feb 13 '21

[removed] — view removed comment

60

u/TangibleLight Feb 13 '21

https://realpython.com/python-metaclasses/

In short: A class is an object that, when called, produces an instance. A metaclass is an object that, when called, produces a class.

type(type(anything)) will always be a metaclass. The "default" metaclass is type, and you can see this with the rare type constructor.

Suppose you have a class like this:

class Square:
  def __init__(self, w):
    self.w = w

  @property
  def area(self):
    return self.w ** 2

s = Square(5)
print(s.area)

Under-the-hood, what's happening with that class Square: syntax is something more like this, using the type constructor. (except that I've changed the methods to lambdas so I can define them in-line)

Square = type('Square', (), {
  '__init__': lambda self, w: setattr(self, 'w', w),
  'area': property(lambda self: self.w ** 2)
})

s = Square(5)
print(s.area)

A metaclass allows you to use something other than type here. class Foo(metaclass=Meta): uses something like Foo = Meta('Foo', ...) under the hood.

17

u/lifebytheminute Feb 14 '21

I was just dreaming about this last night and was like, “surely people have done this before.” Then I wake up and I’m like, “oh yea people do this all the time.” Still freaks me out.

1

u/selling_crap_bike Feb 15 '21

All the time? Could you give an example of where using metaclasses would be useful?

2

u/lifebytheminute Feb 15 '21

Nope, I don’t know how to use them, I just hear about people using them. Sorry.

6

u/wasmachien Feb 14 '21

Classes are also objects, and since every object has a class, a class also has a class. They are called metaclasses.

1

u/sweettuse Feb 14 '21

a class is a blueprint for an instance of a class and a metaclass is a blueprint for a class

0

u/notParticularlyAnony Feb 14 '21

Something you will never use that people will throw out there in order to show off.

1

u/TangibleLight Feb 14 '21

You're right that you essentially never have to use them, but it's still good to know how they work. Understanding the type system in any language is important, and it's good to know they exist in the rare case you're trying to do something that could be solved with them.