简体   繁体   English

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

[英]Grabbing the name of an instance in a class in python

I have a class that is set up like this` 我有一个这样设置的课程`

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

And I am given an instance like this 我得到了这样的一个实例

porsche = Vehicle(2, 4, "gas")

what I can't figure out is how to use the instance "porsche" to write out to the screen the names of each self initialization in the " __init__ " section. 我不知道的是如何使用实例“ porsche”将“ __init__ ”部分中每个自我初始化的名称写到屏幕上。

The desired output is a sentence like this: 所需的输出是这样的句子:

"I have a Vehicle. It has seats, wheels, and an engine."

Where seats wheels and engine are coming from the class. 那里的座位轮和发动机都来自该班。

I retrieved Vehicle and put it into the string using this: 我检索了Vehicle并使用以下命令将其放入字符串中:

porsche.__class__.__name__

But for the life of me can't figure out how to get each self. 但是对于我的一生,无法弄清楚如何获得每个self. object 宾语

Your question seems to be asking how you can know the attribute names on your object. 您的问题似乎在询问如何知道对象的属性名称。 For simple objects (without slots), then its enough to inspect __dict__ . 对于简单对象(无插槽),则足以检查__dict__ So start with something like this: 所以从这样的事情开始:

def show(x):
    return "I have a {}. It has {}".format(type(x).__name__, ", ".join(x.__dict__))

Then 然后

>>> show(Vehicle(1, 1, 1))
'I have a Vehicle. It has seats, wheels, engine'

You can use obj.__dict__ to access an instance's fields / members / data attributes . 您可以使用obj.__dict__来访问实例的字段/成员/数据属性

Are you looking for something like this? 您是否正在寻找这样的东西?

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())

Output: 输出:

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

Note that these field names will be in an arbitrary order (dicts are unordered in Python), not necessarily in the order you defined them in __init__() . 请注意,这些字段名称将采用任意顺序(在Python中字典是无序的),而不一定是您在__init__()定义的顺序。

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

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