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.

2
  • Does this answer your question? Are static class variables possible in Python? Commented Jan 7, 2020 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 Commented Jan 7, 2020 at 16:04

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Seems a bit weird, but answers my question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.