在python中获取类中实例的名称

在python中获取类中实例的名称,python,Python,我有一个这样的班级` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine 我有一个这样的例子 porsche = Vehicle(2, 4, "gas") 我搞不懂的是如何使用实例“porsche”在屏幕上写出“\uuuuuu init\uuuu”部分中

我有一个这样的班级`

class Vehicle:
    def __init__(self, seats, wheels, engine):
        self.seats = seats
        self.wheels = wheels
        self.engine = engine
我有一个这样的例子

porsche = Vehicle(2, 4, "gas")
我搞不懂的是如何使用实例“porsche”在屏幕上写出“
\uuuuuu init\uuuu
”部分中每个自我初始化的名称

所需的输出是这样一句话:

"I have a Vehicle. It has seats, wheels, and an engine."
def show(x):
    return "I have a {}. It has {}".format(type(x).__name__, ", ".join(x.__dict__))
座椅、车轮和发动机都来自于课堂

我检索了车辆并使用以下方法将其放入字符串:

porsche.__class__.__name__

但是对于我的生活来说,我不知道如何获得每个
自我。
对象你的问题似乎是问你如何知道对象上的属性名称。对于简单的对象(没有插槽),检查
\uuu dict\uuu
就足够了。因此,请从以下内容开始:

"I have a Vehicle. It has seats, wheels, and an engine."
def show(x):
    return "I have a {}. It has {}".format(type(x).__name__, ", ".join(x.__dict__))
然后


您可以使用
obj.\uuu dict\uu
访问实例的

你在找这样的东西吗

class Vehicle:
    def __init__(self, seats, wheels, engine):
        self.seats = seats
        self.wheels = wheels
        self.engine = engine

    def description(self):
        # 'Vehicle'
        name = self.__class__.__name__

        # ['seats', 'wheels', 'engine']
        field_names = self.__dict__.keys()

        return "I have a %s. It has these fields: %s" % (
            name, ', '.join(field_names))


porsche = Vehicle(2, 4, "gas")
print(porsche.description())
输出:

I have a Vehicle. It has these fields: engine, wheels, seats

请注意,这些字段名的顺序是任意的(在Python中,dict是无序的),而不一定是您在
\uuu init\uuu()中定义的顺序

类实例没有内部名称。如果你想要这样的东西,把它添加到你的
\uuuu init\uuuu
中。你的问题主体似乎与标题没有任何关系。对不起,我只是不知道如何提问。我不知道;我不知道你如何能抓住这些名字(座位、轮子、引擎)并在字符串中使用它们