Use format function for Python class

Asked 1 years ago, Updated 1 years ago, 102 views

I'm going to pre-define the function in the class and import it at any time to use it.

The desired output value is "m1: How is your relationship going? g1 ah?"

def romance(self, listener):
    print("{}): How's your relationship going? {}Oh?".format(self, listener))

I tried to organize it in this format, but there are times when I keep getting errors and when I import it, it says that the function is not defined, so I post a question like this

I would appreciate it if you could let me know if there is another way not to use the format function.

python function format class

2022-09-21 16:38

2 Answers

I don't fully understand the question.

I've written as much as I understood.

In [1]: class My: 
   ...:     ...:     def romance(self, listener): 
   ...:         print("{}): How's your relationship going? {}Oh?".format(self, listener)) 
   ...:     ...:     def __str__(self): 
   ...:         ...:         return self.__class__.__name__

In [2]: My().romance ("Any")                                                                                        
My: How's your relationship going? Who are you?


2022-09-21 16:38

Hello.

If it's not a format function, why don't we use the fstring?

s1 = 'A'
s2 = 'B'

# # format
# {}If you have two, you have to add two variables, too!
print('{}: How's your relationship going? {}Ah.format(s1, s2))

# # fstring
print(f'{s1}: How's your relationship going? {s2} Ah')

And don't think of self as a parameter

def romance(self, listener1, listener2):
    print("{}): How's your relationship going? {}Ah?".format(listener1,listener2)

I don't think there will be any errors if I write it like this.


2022-09-21 16:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.