I was reading this answer to the question What are metaclasses in Python? when I learned that classes in Python don’t have to be created using the class
keyword. For example, to quote the aforementioned answer:
>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
>>> print(MyShinyClass)
<class '__main__.MyShinyClass'>
This made me wonder: now that classes are not necessarily what you define using the class
keyword, then what exactly is a class?
Most discussions about Python classes that I recall having read seem to assume a common understanding of what they are, or at best provide descriptions rather than definitions. For example, to say that they are blueprints for creating objects is not to give a definition. The following seems to mean that by defining a function I create instances of the function
class without knowing it existed. Even if I did I would not know how to use it as a blueprint.
>>> def f():
... pass
...
>>> type(f)
<class 'function'>
I think what I want know is this:
Suppose I’m going to give you an object X and ask whether it’s a class or not. Yes or no. You need to come up with a test before seeing X. (You are not allowed to see X first and then devise a test after having seen it.)
I suppose this test would be equivalent to a definition of classes. Is there such a test/definition?
8
This could be really unprofessional but I defined class for myself as a grouping method for multiple functions. so instead of processing all the functions in your codes when you run them, only those functions of each certain class (or in other name: class objects) you want would be run and tested. let alone better arrangement of your codes, this can be of greater importance when the number of line of codes are so much and processing time is valuable.
To differentiate between a function and class, you can use type() module. I don’t know any other method rather than that. Good luck.
4