When should I use parentheses in Python?

Asked 2 years ago, Updated 2 years ago, 17 views

I don't know why there is no parenthesis in the string.ascii_lowercase, key = text.count part

From what we've learned so far, parentheses are essential whether or not variables are included, such as text.count and text.lower() I knew it, but if you put parentheses here, an error occurs. How does it work?

import string
text = text.lower()
return max(string.ascii_lowercase, key = text.count)

python

2022-09-22 18:33

1 Answers

Hello!

First, parentheses are required for invocation.

If you use it without parentheses, it's just an object (because the function is also an object!))

Sometimes, you turn over objects without brackets

import string
text = 'Hello'.lower()  

print(string.ascii_lowercase) # 'abcdefghijk..'
print(text.count('l') #hello has two ls, so 2 is taken
print(max('abc')) #c is taken

print(max('ael', key=text.count)) 
# a goes in first, so text.count('a') 0
# Since e is text.count('e'), one
# If you do text.count('l), you get two
# That is, max(0, 1, 2) is 2 is l, so l is finally returned
print(max(string.ascii_lowercase, key=text.count))
# This will have an "l" too, right? (2 is the maximum value)

In the max() function that I write with key, if I call instead of receiving the function object, I can't process it multiple times sequentially It's over after I page you.)

When you turn over a function object, you call the function object from the already created max function several times in parentheses () to find the intermediate result value and find the real max value of it

Use it this way

1

def str_length(s):
    return len(s)

print(max('a', 'abc', 'ab', key=str_length)) #3, not 'abc'!

2

class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __str__(self):
        return 'Data[%s]' % self.id


def get_data_id(data):
    return data.id

list_objects = [Data(1), Data(2), Data(-10)]
print(max(list_objects, key=get_data_id))

Have a nice day


2022-09-22 18:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.