I have created a class in Python with classes nested in it:
class example:
class example_in_class:
exampleKey = "exampleItem"
exampleKey2 = "exampleItem2"
thisOne = "thisone"
exampleKey3 = "exampleItem3"
exampleKey4 = "exampleItem4"
class example_in_class2:
exampleKey = "exampleItem2"
exampleKey2 = "exampleItem22"
thisOne = "NOTthisone"
exampleKey3 = "exampleItem32"
exampleKey4 = "exampleItem42"
Now I want to see if I can find the item "thisone"
without specifying the class.
Is it like example.include("thisone")
or something?
I have searched this all over google but it isn't a human so I don't know how to word it so it understands...
I don't know why you would ever want to do such a thing, but here it is:
def find_thisone(cls):
for attr in cls.__dict__.values():
if type(attr) != type:
continue
if 'thisone' in attr.__dict__.values():
return attr
This function will find you the nested class that has a string attribute with value thisone
:
>>> find_thisone(example)
__main__.example.example_in_class
But for real, you're better off heeding the suggestions in the comments.
Edit: An explanation: .__dict__
allows you to iterate through an object's attributes just like a dictionary object. The dictionary has keys()
and values()
. The names of the nested classes will be in the keys()
, and the actual classes will be in the values()
. By checking whether the type()
of each value is itself a type
, i.e. a class, we can get at the nested classes without worrying about any other attributes of the outer class. Then we likewise access the attributes of the nested class using .__dict__.values()
and check if the string 'thisone'
is among them. If so, we've found the right nested class.
Inserting large amount of data with psycopg2 not working properly
linked list algorithm: Reverse Linked List In Pairs by Python [closed]
Is there a way to run a function when my Discord bot joins a server? - Discord.py Rewrite
Implementing follower system using a many to many field through a model
I have an SQLite file of 18 million values, which I have changed into CSV files because It was not loading
As the title states, is there a way to do something like this:
I am using the Gaussian Processes of scikit-learn to estimate behavior of a black box likelihood function f()
Generator objects in Python are required to have a close method that exists to ensure that context managers are exited and try