I am confused with built-in method in Python.
For instance, what is the some_string.lower()
and str.lower(some_string)
and how are they different?
str
is the name of the class of all strings in Python. str.lower
is one of its methods.
If you call lower
on one of its instances (e.g. 'ABC'.lower()
), you call a bound method, which automatically sends the called object as the first argument (usually called self
).
If you call lower
on the class itself (i.e. you use str.lower()
), then you call an unbound method, which doesn't provide the self argument automatically. Therefore, you have to specify the object to act upon by yourself.
If all of this seems hard to understand, it will be easier when you consider how methods are defined in the classes. Let's say we create our own very simple class, which represents a point (X,Y coordinate in space). And has a show()
method to print the point.
class Point:
"""This is the constructor of Point"""
def __init__(self, x, y):
# Save arguments as field of our class instance (self)
self.x = x
self.y = y
def show(self):
print self.x, self.y
# We now create an instance of Point:
p = Point(1.0, 2.0)
# We now show p by calling a bound method
p.show()
Note that we didn't have to specify the self argument (so p.show() was called with no arguments). In reality, the previous call was more or less equivalent to this:
Point.show(p)
They're not entirely equivalent, but that's a more advanced topic. One of the simplest cases when they will not be equivalent is if you change the value of p.show after creating the object, for instance:
p.show = 4
Now, p.show()
won't even compile, since p.show is not a function anymore, but an integer! However, Point.show(p)
would still be unchanged, since we only modified the show
attribute in the class instance (p
) and not in the class itself (Point
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With