-1

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

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Jack Ingram
  • 23
  • 1
  • 3

2 Answers2

1

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'
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
1

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

Lukas Graf
  • 30,317
  • 8
  • 77
  • 92