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

前端 未结 4 1880
佛祖请我去吃肉
佛祖请我去吃肉 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:03

    There are different ways to approach your problem.

    The simplest I can fathom is if you can change the class man, make it accept an optional name in its __init__ and store it in the instance. This should look like this:

    class man:
        def __init__(number, color, name="John Doe"):
            self.name = name
            # rest of your code here
    

    That way in your function you could just do with:

        return guy1.name
    

    Additionnally, if you want to go an extra step, you could define a __str__ method in your class man so that when you pass it to str() or print(), it shows the name instead:

        # Inside class man
        def __str__(self):
            return self.name
    

    That way your function could just do:

        return guy1
    

    And when you print the return value of your function it actually prints the name.


    If you cannot alter class man, here is an extremely convoluted and costly suggestion, that could probably break depending on context:

    import inspect
    def competition(guy1, guy2, counter1=0, counter2=0):
        guy1_name = ""
        guy2_name = ""
        for name, value in inspect.stack()[-1].frame.f_locals.items():
            if value is guy1:
                guy1_name = name
            elif value is guy2:
                guy2_name = name
        if counter1 > counter2:
            return guy1_name
        elif counter2 > counter2:
            return guy1_name
        else:
            return "Noone"
    

提交回复
热议问题