How do I get a function factor as a variable name in Python?

Asked 2 years ago, Updated 2 years ago, 14 views

The function factor is usually passed to a normal value, right? By the way, I want to use the function factor as the instance variable name.

For example, if you put abc in the foo function factor in class A, I want to assign 5 to the instance variable self.abc.

//
  class. : a
    def foo(XXXX):
    XXXXXX
    XXXXXX=5

B = A()
B.foo(abc)
B.abc
# output of 5.

How can I organize that X-marked part to get the results I want?

python

2022-09-21 18:35

1 Answers

You can use a function called reflection.

>>> class Foo:
...     ...     def myFunc(self, fieldName):
...         ...         setattr(self, fieldName, 5)
...    
... 
>>> f = Foo()
>>> f.myFunc('abc')
>>> f.abc
5


2022-09-21 18:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.