When I create a class Test defining one method “a”, a object Test, whose type is type ,is created. The dir function give-us the names of the attributes/methods of an object. But when I code:
class Test(): def a: pass print(dir(Test))
I get:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
from where did this “a” come from?
I thought “a” would be a method from a object whose class is Test, but the Test object itself have the same method, How?
Advertisement
Answer
I thought “a” would be a method from a object whose class is Test, but the Test object itself have the same method, How?
Classes are objects. They can and do have attributes, including callable ones, just like any other object. They obtain their initial complement of these from the execution of their class
block. In particular, class objects get a callable attribute for each function def
ined in their class
block. That’s just how it works.
Classes’ callable attributes can be called directly, and sometimes they are intended to be used that way. Those intended to be called directly are commonly called “class methods”.
The magic, to the extent that there is any, is in invoking methods on instances: when instance
is an instance of class Klass
, and instance
does not have its own attribute method
, but Klass
has a callable attribute by that name, then Python interprets instance.method()
as Klass.method(instance)
. That can be done explicitly, too, as if method
were a class method — in that sense, Python does not make a strong distinction between class and instance methods.