[英]Is there a way to turn a class object name into the string associated with it?
So in my program, a certain function (good_function()) needs to use the string name (attribute_name) of an object when referencing an attribute(object_name.attribute) of an object(object_name).所以在我的程序中,某个function(good_function())在引用对象(object_name)的属性(object_name.attribute)时需要使用object的字符串名称(attribute_name)。 This attribute is also another object from a different class.
此属性也是来自不同 class 的另一个 object。 However, when I pull out this attribute to be used, it brings up the class object name (< main .Class2 object at abcde12345>) instead of the name of the attribute (attribute_name).
但是,当我拉出要使用的此属性时,它会显示 class object 名称(< main .Class2 object at abcde12345_name)而不是(属性名称的名称) The current output and setup is as follows.
当前的 output 和设置如下。
class Class():
def __init__(self, attribute):
pass
class Class2():
pass
attribute_name = Class2()
object_name = Class(attribute_name)
object_name.attribute = attribute_name
def good_function(thing):
#doesn't really matter
pass
good_function(object_name.attribute)
print(object_name.attribute)
>>> <__main__.Class2 object at abcde12345>
It reads "object_name.attribute"(attribute_name) "as the attribute_name"'s object ID name thingamajiggy (< main .Class2 object at abcde12345>) instead of just "attribute_name".它读取“object_name.attribute”(attribute_name)“作为attribute_name”的object ID名称thingamajiggy(< main .Class2 object at abcde12345>),而不仅仅是“attribute_name”。 So my question is: Is there a way to translate the callsign (< main .Class2 object at abcde12345>) into the "attribute name" to which it corresponds?
所以我的问题是:有没有办法将呼号(< main .Class2 object at abcde12345>)翻译成它对应的“属性名称”? (see desired output below) Thanks in advance, I hope this wasn't too confusing, and I'll be as active as I can in responses.
(请参阅下面的所需 output)提前谢谢,我希望这不会太混乱,我会尽可能积极地回应。 The desired output and setup is below.
所需的 output 和设置如下。
cclass Class():
def __init__(self, attribute):
pass
object_name.attribute = 'attribute_name'
def magic_function(object):
#solve for here
return object
def good_function(thing):
#doesn't really matter
pass
variable = magic_function(object_name.attribute)
good_function(variable)
print(variable)
>>> attribute_name
If I'm understanding correctly, then I don't think what you want is possible, assuming the actual reference attribute is just a native type.如果我理解正确,那么假设实际的引用属性只是本机类型,那么我认为您想要的东西是不可能的。
However, if you made the attribute an instance of your own custom class then any instance could implement the __str__
method to display whatever you wanted:但是,如果您将属性设置为您自己的自定义 class 的实例,那么任何实例都可以实现
__str__
方法来显示您想要的任何内容:
class MyClass():
def __str__(self):
return 'MyClass str'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.