Accessing an object using eval in python
Budget: $10 – $30 USD
How can I get the code below to print obj2's variable (i.e., the data frame, df) using the eval function? The sample code is as follows:
________________________________________________________
import pandas as pd
class Sample:
def __init__(self):
self.df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [10, 2, 1, 8]},
index=['falcon', 'dog', 'spider', 'fish'])
def print(self):
eval("obj2.df.head()")
def main():
obj1 = Sample()
obj2 = Sample()
obj2.print()
if __name__ == '__main__':
main()
________________________________________________________
When I try running the program, it throws the following error:
NameError: name 'obj2' is not defined
I need to access the df variable belonging to obj2 using the eval function.Please stick to providing a solution ONLY using the eval() function and NOT using the getattr() function. I have attached the code along with this project. Please refer to sample.py
________________________________________________________
import pandas as pd
class Sample:
def __init__(self):
self.df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [10, 2, 1, 8]},
index=['falcon', 'dog', 'spider', 'fish'])
def print(self):
eval("obj2.df.head()")
def main():
obj1 = Sample()
obj2 = Sample()
obj2.print()
if __name__ == '__main__':
main()
________________________________________________________
When I try running the program, it throws the following error:
NameError: name 'obj2' is not defined
I need to access the df variable belonging to obj2 using the eval function.Please stick to providing a solution ONLY using the eval() function and NOT using the getattr() function. I have attached the code along with this project. Please refer to sample.py