开发者

In Python, what's difference between some_string.lower() and str.lower(some_string)

I am confused with built-in method in 开发者_JAVA技巧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).


The first is a bound method call and the second is an unbound method call.

Think about how you'd write a method like this:

class str:
    ...
    def lower(self):
        # And so on

The first argument is self. If you use this method from an instance (e.g. some_string.lower(), the instance automatically gets passed as the first argument to the method (as self).

However, if you call it from the class (as an unbound method), e..g str.lower(some_string), there is no instance to automatically pass as the first argument. So, instead, some_string gets passed as self and whatever would've been done with the instance in the first case gets done with some_string.

It's never really necessary to use the unbound version, however, as any string will have a lower() method that you can call. The preferred style is to use some_string.lower().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜