简体   繁体   English

如何在函数中打印变量类类型的实际名称?

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

I'm trying to return variable name, but i keep getting this: 我正在尝试返回变量名,但是我不断得到这个:

<classes.man.man object at (some numbers (as example:0x03BDCA50))>

Below is my code: 下面是我的代码:

from classes.man import man

def competition(guy1, guy2, counter1=0, counter2=0):
    .......................
    some *ok* manipulations
    .......................
    if counter1>counter2:
        return guy1

bob = man(172, 'green')
bib = man(190, 'brown')
print(competition(bob , bib ))

Epilogue 结语

If anyone want to, explain please what I can write instead of __class__ in example below to get variable name. 如果有人愿意,请在下面的示例中解释我可以写些什么而不是__class__以获得变量名。

def __repr__(self):
        return self.__class__.__name__

Anyway, thank you for all of your support 无论如何,谢谢您的支持

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. 我可以理解的最简单的方法是,如果可以更改class man ,使其在其__init__接受一个可选名称,然后将其存储在实例中。 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: 另外,如果您想采取额外的步骤,则可以在类man定义__str__方法,以便在将其传递给str()print() ,它改为显示名称:

    # 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: 如果您不能更改class man ,这是一个非常复杂且代价高昂的建议,根据上下文可能会中断:

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"

Valentin's answer - the first part of it at least (adding a name attribute to man ) - is of course the proper, obvious solution. Valentin的答案-至少是第一部分(向man添加了name属性)-当然是正确的,显而易见的解决方案。

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... 现在第二部分( inspect.stack hack),它充其量是脆弱的-我们感兴趣的“变量名称”可能不一定在第一个父框架中定义,而FWIW它们也可能来自一个字典等...

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: 同样,绝对不是comment competition()函数负责处理此问题(谢谢,不要将域层与表示层混合使用), 并且这完全没用,因为调用者代码可以轻松地自己解决这一部分:

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!")

Python prints the location of class objects in memory if they are passed to the print() function as default. 如果默认将类对象传递给print()函数,Python将打印类对象在内存中的位置。 If you want a prettier output for a class you need to define the __repr__(self) function for that class which should return a string that is printed if an object is passed to print() . 如果要为一个类提供更漂亮的输出,则需要为该类定义__repr__(self)函数,如果将对象传递给print() ,则该函数应返回要打印的字符串。 Then you can just return guy1 然后你就可以return guy1

__repr__ is the method that defines the name in your case. __repr__是根据您的情况定义名称的方法。 By default it gives you the object type information. 默认情况下,它为您提供对象类型信息。 If you want to print more apt name then you should override the __repr__ method 如果要打印更多的apt名称,则应重写__repr__方法

Check below code for instance 例如检查以下代码

class class_with_overrided_repr:
    def __repr__(self):
        return "class_with_overrided_repr"

class class_without_overrided_repr:
    pass

x = class_with_overrided_repr()
print x    # class_with_overrided_repr

x = class_without_overrided_repr()
print x    #  <__main__.class_without_overrided_repr instance at 0x7f06002aa368>

Let me know if this what you want? 让我知道你想要什么吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM