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:
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()
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.