Search code examples
pythonclassinstantiationidentifier

Python - Instantiating a class without assigning a name to the instance


A Python newbie here!

The example below is about the difference between instantiating a class then assigning a name to the instance, and instantiating without assignment.

In the last three lines of the example, the method is first called on the instance (my_city), then it is called without an instance. So:

  1. What is the difference?
  2. When is that considered useful or preferable approach?
  3. Since everything in Python is an object, what or where is the object in the last line?
class City:
    def __init__(self, name):
        self.name = name

    def show_city_name(self):
        print(self.name)

my_city = City("Tokyo")
my_city.show_city_name()

City("Tokyo").show_city_name()

Solution

  • The City("Tokyo").show_city_name() statement results in creation of temporary instance of type <class '__main__.City'> on which the show_city_name() method is called.

    So, the instance is still created, thought it does not bind with any reference to it. We can say that object in in the City("Tokyo") expression. Take a look at this:

    >>> type(City('Foo'))
    <class '__main__.City'> # Means it is an instance of the City class
    

    Almost the same type of approach (seemingly invoking a method directly on a class) can be seen when you have static class methods or @classmethod decorator. For example:

    class Circle:
        def __init__(self, radius):
            self.radius = radius
    
        # other definitions
    
        @classmethod
        def unit_circle(cls):
            return cls(1)
    
    unit_c = Circle.unit_circle()
    
    print(unit_c.radius)
    # Prints 1
    

    This is more correct way and more probable way of doing the same thing in real world code.