This question is about the id
method in Python and if a class method is the same instance for the class object itself and any object instances created from that class.
Sample code:
class Person:
def __init__(self, name: str) -> None:
self.name = name
def name_as_upper(self) -> str:
return self.name.upper()
p = Person("john")
p2 = Person("sarah")
print(
id(p.name_as_upper), id(p2.name_as_upper), id(Person.name_as_upper)
) # first two are the same, last one different
print(p.name_as_upper()) # JOHN
print(Person.name_as_upper(p)) # JOHN
Person.name_as_upper = (
lambda self: self.name.upper() + " - suffix"
) # "point" name_as_upper method object to different method
print(p.name_as_upper()) # JOHN - suffix
print(Person.name_as_upper(p)) # JOHN - suffix
In the above example, the ids printed by the calls id(p.name_as_upper)
and id(p2.name_as_upper)
are identical, but the call id(Person.name_as_upper)
is different.
I was expecting all of the ids to be identical. The method object referenced by the name Person.name_as_upper
is different?
I thought a call to a method on an object instance was translated into a call to the method object belonging to the class, i.e.:
p.name_as_upper()
# Would be translated / equivalent to
Person.name_as_upper(p)
When re-assigning Person.name_as_upper
to a new method (the lambda expression in the sample code above) the change is seen also by the instance p
.
So p.name_is_upper
still is “the same” as Person.name_as_upper
.
Thankful for any clarifications to my (lack of) understanding.