Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a type class using type class in python

I was reading this interesting post on metaclasses What is a metaclass in Python?. The accepted answer shows how to create a class using type with the following signature.

type(name of the class, tuple of the parent class (for inheritance, can be empty), dictionary containing attributes names and values)

I tried to create 'type' class using the above signature and I was surprised that I was allowed to create one in the first place! Your views are appreciated!

type = type('type',(),{});

Second, after I created a type class using the above syntax, I was not able to do

myclass = type('myclass',(),{}); 

and type = type('type',(),{});

I got an error saying

Traceback (most recent call last): File "", line 1, in TypeError: object.new() takes no parameters

But, when I tried to the following, I could succeed.

class myclass(object):
    pass

I am puzzled coz, according to my understanding the above snippet should invoke type in an attempt to create the class 'myclass'. So whats going on!? Am I missing some detail?

like image 241
Karthick Avatar asked Apr 22 '26 14:04

Karthick


1 Answers

You've shadowed type with type with type = type('type',(),{})

Note that semi-colons are redundant in Python.

So you're creating a type that can't do anything.

That's why the later type breaks.

like image 51
Jon Clements Avatar answered Apr 24 '26 03:04

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!