Get the value of variables in dir(class) [duplicate] - python

This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 8 years ago.
I'm writing a class in python that groups a bunch of similar variables together and then assembles them into a string. I'm hoping to avoid having to manually type out each variable in the generateString method, so I want to use something like:
for variable in dir(class):
if variable[:1] == '_':
recordString += variable
But currently it just returns a string that has all of the variable names. Is there a way to get at the value of the variable?

You can use the getattr() function to dynamically access attributes:
recordString += getattr(classobj, variable)
However, you probably do not want to use dir() here. dir() provides you with a list of attributes on the instance, class and base classes, while you appear to want to find only attributes found directly on the object.
You can use the vars() function instead, which returns a dictionary, letting you use items() to get both name and value:
for variable, value in vars(classobj).items():
if variable[:1] == '_':
recordString += value

Related

What are the static variables of a function in Python? [duplicate]

This question already has answers here:
Can a function have an attribute?
(2 answers)
Closed 1 year ago.
In the Python code portion of Inorder predecessor and successor for a given key in BST, something of this sort is done. Can someone explain this part of code?
P.S. I know what static variables are, it's just that its implementation in the way shown is confusing me.
# Static variables of the function findPreSuc
findPreSuc.pre = None
findPreSuc.suc = None
In Python, everything is object. And every object has member fields that can be accesed. This is stored in special field called __dict__. You can acces object attributes in various ways:
obj.field # direct attribute access
obj.__dict__["field"] # attribute dictionary access
getattr(obj, "field") # get attribute
Functions are objects too and thus they also have a __dict__ field. But they have unique behavior from other objects - if you try access field that doesn't exists with normal object, you will get error. If you try same thing with function, function will add new field instead (like how function create new local variables)
TL;DR: functions are objects too, and they can have fields like objects. These fields don't change between callings

I am new to python, and realized that i can assign print i.e. an inbuilt function as a variable [duplicate]

This question already has answers here:
How to restore a builtin that I overwrote by accident?
(3 answers)
Closed 2 years ago.
I am new to python, and realized that i can assign print i.e. an inbuilt function as a variable, then when i use print('hello world')this shows the exact error that i faced
I am familiar to c++ and even in that we were never allowed to use an inbuilt function as a variable name.
those were the fundamental rules for naming a variable
If python.org has issued the new version I'm sure they would have done it for a reason, bbut i want to know how do i access my print statement after assigning a value to it?
you won't be able to access your print function unless you do hacky things, which I recommend not to do them in the middle of your code.
Also it is good to know that python (as c++) has scopes for variables, and variables "die" and they are no longer accessible when scope ends. For instance:
def change_print_value():
print = 3
change_print_value()
print('Print works as expected')
It is a good practice to avoid using reserved keywords as variable names. Any IDE has the keywords highlighted, so you can easily realize when you are using a keyword where you shouldn't.
print is not part of the reserved keywords list in python. Here's a comprehensive list of reserved words.
Functions are first class objects in python, so that means they can be treated and manipulated as objects. Since print is a function (and an object), when you call print = 1, you reassign the variable print to have a value of 1, so the functionality "disappears".

How to convert a string to a class name? [duplicate]

This question already has answers here:
Convert string to Python class object?
(10 answers)
Closed 4 years ago.
I checked I have a string whose content is a function name, how to refer to the corresponding function in Python? but it is not the question I want to ask.
The question is: I have a string 'ABC' and I want to create an instance of class ABC as:
my_obj = ABC ()
The input 'ABC' is read from Python arguments (argparse).
The class is already defined and imported.
You can use a dictionary:
d = {'ABC': ABC} # where ABC is the class object
my_obj = d['ABC']()
This should be preferable to solutions using global (poor practice) and eval (security risks).
This may seem cumbersome until you realise that classes and class instances are first class objects in Python. You should never rely on evaluating strings to call a Python object. Be explicit, even if it's not elegant.

Python - Instantiating lists,dicts, and objects with a string [duplicate]

This question already has answers here:
Using a string variable as a variable name [duplicate]
(3 answers)
Closed 6 years ago.
Python 3.4.2 question, I have extensively looked for an answer to this, cannot find it.
I am trying to create python objects (or whatever you would call lists, dicts, and classe/object instantiations) by assigning strings to the definition. Or put differently, I want to use strings on the left hand side of the assign equation.
For instance, if we have a class, and an assignment/instantiation:
class char_info:
def __init__(self):
self.name = 'Joe'
self.mesh = 'Suzanne'
newchar = char_info()
print (newchar.name)
Joe
I would like to use using a string from another source (say a list) as the instantiated name, instead of "newchar". However, I am not sure the syntax. I need to reference this string on the left hand side of the equation. Furthermore, how do I reference this in later code since I wouldn't know the name beforehand, only at runtime?
Obviously this doesn't work:
list = ['Bob', 'Carol', 'Sam']
# list[0] = char_info() #this doesn't work, it would
# try assigning the value of char_info() to the item in [0]
str(list[0]) = char_info() #also doesn't work, obviously
print (str(list[0]) #obviously this is wrong, but how do you reference?
location: :-1
Error: File "\Text", line 2
SyntaxError: can't assign to function call
What I want is to have say, a loop that iterates over a list/dict and uses those strings to instantiate the class. Is there any way to do this? Special syntax I am not aware of?
By the way, this same thing should be the solution to do the same thing with creating list names, dict names, etc. Heck, even something simple like enumerating a variable name or assigning variables out of a list. How do you dynamically define the assignment name?
You can use exec i.e. exec(list[0] + "=char_info()") but this is a bad idea. Using a dictionary is better:
chars = {}
chars[list[0]] = char_info()
What I want is to have say, a loop that iterates over a list/dict and
uses those strings to instantiate the class. Is there any way to do
this?
class char_info:
def __init__(self, name):
self.name = name
list_names = ['Bob', 'Carol', 'Sam']
list_char_info = [char_info(name) for name in list_names]
The above code will instantiate a class for each name in the list of names

python introspection - get name of variable passed to function [duplicate]

This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 7 years ago.
I'd like to be able to access the name of a variable that is passed to a function as e.g.
def f(x):
'''Returns name of list/dict variable passed to f'''
return magic(x)
>>a = [1,2,3]
>>print( f(a) )
'a'
>>print( f(2) )
None
I suspect this is possible using Python introspection but I don't know enough to understand the inspect module. (NB I know that the need for a function like magic() is questionable, but it is what I want.)
Actually, this is not possible. In Python names and values are quite separate. Inside f, you have access to the value of x, but it is not possible to find out what other names other functions might have given to that value.
Think of names as being somewhat like pointers in C. If you have a pointer, you can find out what object it points to. But if you have the object, you cannot find out what pointers are pointing to it.

Categories

Resources