简体   繁体   中英

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.

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:

porsche.__class__.__name__

But for the life of me can't figure out how to get each 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__ . 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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