Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python method accessor creates new objects on each access?

Tags:

People also ask

What is an accessor method in Python?

Accessor Method: This method is used to access the state of the object i.e, the data hidden in the object can be accessed from this method. However, this method cannot change the state of the object, it can only access the data hidden. We can name these methods with the word get.

When a new instance of a class is created which method gets called?

A function like Turtle or Point that creates a new object instance is called a constructor, and every class automatically provides a constructor function which is named the same as the class.

What method is called when an object is created with the new method?

Instantiation: The new keyword is a Java operator that creates the object. As discussed below, this is also known as instantiating a class.

What is __ set __ in Python?

The __set__() method is invoked when the value is set to the attribute, and unlike the __get__() method, it returns nothing. It has two arguments apart from the descriptor object itself, i.e., the instance which is the same as the __get__() method and the value argument, which is the value you assign to the attribute.


When investigating for another question, I found the following:

>>> class A:
...   def m(self): return 42
... 
>>> a = A()

This was expected:

>>> A.m == A.m
True
>>> a.m == a.m
True

But this I did not expect:

>>> a.m is a.m
False

And especially not this:

>>> A.m is A.m
False

Python seems to create new objects for each method access. Why am I seeing this behavior? I.e. what is the reason why it can't reuse one object per class and one per instance?


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!