1

I would like to have an instance of a class statically available. An example below:

class Car:

    ford = Car(brand='Ford')
    mercedes = Car(brand='Mercedes')
    bmw = Car(brand='BMW')

    def __init__(self, brand: str):
        self.brand = brand

This would allow me to do Car.ford for instance. However, it says the class Car doesn't exist. Is this possible in Python?

I have seen other posts explaining how static variables relate to classes and instances, but I was unable to find a post about a static variable of an instance of that same class. So the following example is not what I mean:

class Car:

    wheels = 4

    def __init__(self, brand: str):
        self.brand = brand


Car.wheels      # Will give me 4

trike = Car(brand='Trike')
trike.wheels    # Will give me 4
trike.wheels = 3
trike.wheels    # Will give me 3

Car.wheels      # Still gives me 4

I'm talking very specific about a static variable of an instance of that class.

Bram
  • 2,718
  • 1
  • 22
  • 43
  • Does this answer your question? [Are static class variables possible in Python?](https://stackoverflow.com/questions/68645/are-static-class-variables-possible-in-python) – APhillips Jan 07 '20 at 16:02
  • No, sorry. I saw that post, but it doesn't talk about a static variable of an instance of the class itself. I tried to be as specific as possible, but the question might be vague, not sure – Bram Jan 07 '20 at 16:04

1 Answers1

2

You can do it this way

class Car:
    def __init__(self, brand: str):
        self.brand = brand

Car.ford = Car(brand='Ford')
Car.mercedes = Car(brand='Mercedes')
Car.bmw = Car(brand='BMW')
Mickael B.
  • 4,755
  • 4
  • 24
  • 48