0

Suppose I have a class called Circuit, and a dictionary containing data about each circuit component:

components = {
    'V1': [ ... ], 
    'L1': [ ... ], 
    'R1': [ ... ], 
    'R2': [ ... ], 
    ...
}

I want to define child objects Circuit.V1, Circuit.L1, and so on.

The crux of the problem is that I have strings ("V1", "L1", ...) that need to be converted into identifiers. The necessary identifiers would be different depending on what data is passed to the constructor of Circuit, so I can't just hard-code them.

Is this possible, and if so, how do I do this?

I haven't been able to find any information on this (searching just brings up basic info on valid identifier names and such). I have found this page but the question was never directly answered.

Right now I can access my circuit component object like Circuit.components['V1'], but that seems a little clunky and I would prefer Circuit.V1.

Edit: The term for the thing I was trying to do is dynamic attribute assignment. Adding this so that others like me who didn't know what keywords to search for can more easily find information.

2 Answers 2

3

Although not recommended, you can use the __setattr__ dunder method:

class C:
    ...

c = C()

c.__setattr__("V1", 1)

print("c.V1 = ", c.V1) # c.V1 = 1

In principle this works, but if you want to define attributes in runtime (you do not know the name of the attributes beforehand) why would you like to treat them as attributes? I think your dictionary approach is better suited for your use case.

Sign up to request clarification or add additional context in comments.

Comments

0

If we want view like Circuit.V1, you will make the class and create a object of class.. Like:

class Component:
    V1 = 0
    ... 

Circuit = Component() 
Circuit.V1 = 2

But who do this for "beauty"?

Comments

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.