How to print actual name of variable class type in function?

前端 未结 4 1878
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 04:21

I\'m trying to return variable name, but i keep getting this:

Below is my cod

4条回答
  •  暖寄归人
    2021-01-29 05:04

    Valentin's answer - the first part of it at least (adding a name attribute to man) - is of course the proper, obvious solution.

    Now wrt/ the second part (the inspect.stack hack), it's brittle at best - the "variables names" we're interested in might not necessarily be defined in the first parent frame, and FWIW they could as well just come from a dict etc...

    Also, it's definitly not the competition() function's responsability to care about this (don't mix domain layer with presentation layer, thanks), and it's totally useless since the caller code can easily solve this part by itself:

    def competition(guy1, guy2, counter1=0, counter2=0):
        .......................
        some *ok* manipulations
        .......................
        if counter1>counter2:
            return guy1
    
    
    def main():
        bob = man(172, 'green')
        bib = man(190, 'brown')
    
        winner = competition(bob, bib)
        if winner is bob:
            print("bob wins")
        elif winner is bib:
            print("bib wins")
        else:
            print("tie!")
    

提交回复
热议问题