For example, when using the "print" Function it works like this: print (string) However, when using the "lower" Method it works like this: string.lower()
Why isn't lower a normal function that works like this: lower (string)
Is there a reason to implement it as a method? (From my recent reading, a method is really just a function inside of a class.)
Does this have something to do with python strings being immutable so the string has to be "recreated" using a method instead of a function?
I tried lower(string) and it says "NameError: name 'lower' is not defined" which makes sense since it's a method.
People tend to get attracted towards python for its simplicity. It's not just you! Many including me would have been happier if we get the option of using all the function and methods with the same syntax. But we should think about the convenience of the people who create the language as well.
Though these functions would have been created in C-language, For the sake of understanding, I'm writing in python.
Let us assume you want to create several methods to handle strings. The easiest way to design is using OOPS i.e using class and methods. For instance,
class strings:
def __init__(self, text):
self.text = text
def upper():
txt = self.text
for x in txt:
if ord(x) in range(97, 123):
idx = txt.find(x)
x = chr(ord(x)-32)
txt = txt[:idx] + x + txt[idx+1:]
return txt
def lower():
# some code here
def capitalize():
# Some code here
In this way, all the string related codes could have been encapsuled into a single class.(Of course would be written in C, Not in python)
While calling also..
strings('Hello').capitalise()
strings('Hello').upper()
strings('Hello').lower()
Then where has the class name strings gone? Please remember: for the sake of understanding, I took the example from python. Similar kinds of things are available in c and other languages as well. There are methods to omit the class name and considering the parameters as string. What My answer indicates is: 'The reason for this is convenient in grouping and debugging and to explain about the simplicity in grouping and selecting the optimal algorithm'