Python list child classes

Get list of names of child classes in python

Tested on the following structure to ensure that nothing other than class instances would appear in the output:

class Other: pass class commands: a = 2 o = Other() class hello: desc = "says hello" def rand(self): pass class exec: desc = "executes code" def rand(self): pass def clear(self): pass 

Henry Ecker 32900

  • how to use a list of column names to get the indices of each column in python
  • Get image file names with Python pptx
  • how to get list value and count in python
  • How to override list get object in python
  • Get modules names from a package in python
  • How to get rid of \n and split the values surrounding it in a Python list
  • Add list as child of tree with python 3
  • Which is the cleaner way to get a Python @property as a list with particular conditions?
  • Get names and types of a Python module’s attributes
  • How to filtering a list of names from Python when querying through SQLAlchemy
  • How to get a child link on python
  • Python JSON list to get data and retrieve column name
  • get list in python
  • Create Gtk3 Treeview with CellRendererToggle and Names from List with Python
  • Why does my simple python list get reset to None in a for loop?
  • Python dictionary get distinct list counts
  • Initialize two Python classes with same arguments, get different results
  • I am trying to work on the get method of the Linked List in Python where the user puts an index and it gives the data that is in that index
  • Cross merge list elements to get a list of tuples in Python
  • Python itertools get permutations and combinations of a list of lists
  • Get Value of Instance List as a String in python
  • How to get the nth parameter of a list with delimiter space in python
  • python how to find which parent classes define methods of a child object
  • Get list of all paginated URL’s from links in txt file in python requests
  • How to get part of a list in Python without creating a new list?
  • Correct use of super() to .pop() off names from a list in a parent class for each child instance
  • Get the list of all followers ids from twitter using tweepy in python
  • Get parent node using child node lxml python
  • Refering to a list of names using Python
  • python — Get the case-mismatched file names only between two folders in windows
  • How can i get a particular character from a Python list followed by command line argument variable
  • Can’t get Excel drop-down list (combobox) value with python
  • How to get a list of local drives without SUBST’ituted ones in Python / Windows?
  • Get the list of values/entries that are common to all the columns in a dataframe (or a csv file) in python
  • How do I get combinations of a list of words in python
  • Delete all instances of child classes when clearing container in parent class- Python OOP
  • Using python and selenium to get elemnts in to a list or dataframe
  • How to get a particular key value in a list of dictionaries using python
  • Python get all possibilities from word’s list to create a paragraph
  • Python code to get list of application of highest consuming CPU usage in Linux
  • Get a new list from a given index in Python
  • how to get all the hyperlinks from child elements from a specific div container having multiple pages(pagination) using selenium python
  • mongodb: get a 2nd level/ child object with python
  • Python / Boto3 / How can i get a tag list with pagination?
  • Python Setting dataframe names from a string stored in a list
  • Best and quickest way to get top N elements from a huge list in python
  • Python get original list name from class function
  • Rabbitmq/Pika — get a consumer list of a given queue in python
  • How to get a list of nodes ‘inorder’ with python igraph
  • Get list of objects being used with script run dynamically in Python
Читайте также:  What is an integer in javascript

More Query from same tag

  • Can’t move sprite and cant click on image
  • How to apply styling to docxtpl
  • InvalidArgumentError: input_1:0 is both fed and fetched, error with tensorflow, python
  • Problems building a Python extension which uses C++11 features
  • Issue with Selenium,Python
  • Matplotlib monitor — plot values from table every X seconds
  • plt.imshow() display the image inside another image
  • kivy collide_point behavior not as expected
  • one discord bot command makes other command not working
  • How do assign a user’s message to a variable in discord.py?
  • pythonic way to initialize instance variables
  • Python: Manipulate dataframe in user function
  • How to resize TkInter labels absolute size instead additional space with Grid gemetry manager
  • OperationalError: no such column: a
  • How to always track some certain events with logging module? (python)
  • How to find an equation of the trendline of the local maximum and local minimum in my data Time series in Python or R
  • LSTM text generation with Keras: What is diversity?
  • Python inserting into list
  • Is there a way to get a list of all pep8 violations using pycodestyle?
  • How to convert element to Z value using mean, std for each column?
  • Create an entry per item in an iterable of unknown length with Tkinter
  • Serialise objects in azure ML pipeline runs
  • Resetting SQL Window’s length when flag is True?
  • Python 3 tries to run Python 2 on subprocess (Windows)
  • Using findContour and the resulting contours to approximate line segments to find line intersection
  • Encode/decode specific character in string with hex notation using Python 2.7
  • Set a script to suspend and resume after a calculated amount of time
  • Ansicon doesn’t install from python but only from cmd
  • Python — Connection pool runs full in multithreaded execution
  • yolov5 custom trained weights converted to ONNX showing wrong labels
  • Turning if statements to while loops
  • AttributeError: ‘Stud’ object has no attribute ‘sno’ at line no.11
  • why does my csv contain a different format than my script
  • Trying to print all prime numbers below two million
  • __init__.py correct import layout?
Читайте также:  Write content to file python

Источник

Python, List of Children

I want to generate a parent/child datastructure in Python 3.8.10. [GCC 9.3.0] on linux The code is as simple as:

class Member(object): name = "xxx" parent = None children = [] def __init__(self, name): object.__init__(self) self.name = name def setParent(self,p): self.parent = p def addChild(self,ch): self.children.append(ch) ch.setParent(self) def myRelatives(self): str = "I am , my parent is my children are:".format(self.name,self.parent.name if self.parent is not None else "--") print(str) for ch in self.children: print(" ".format(ch.name)) if __name__ == '__main__': A = Member("A") B = Member("B") C = Member("C") D = Member("D") A.addChild(B) B.addChild(C) C.addChild(D) A.myRelatives() B.myRelatives() C.myRelatives() D.myRelatives() 
I am A, my parent is -- my children are: B I am B, my parent is A my children are: C I am C, my parent is B my children are: D I am D, my parent is C my children are: 
I am A, my parent is -- my children are: B C D I am B, my parent is A my children are: B C D I am C, my parent is B my children are: B C D I am D, my parent is C my children are: B C D 

It seems the ‘self.children’ is used as same variable in all instances. Why and how to fix?

>Solution :

You need to set the attributes name , parent , and children in the __init__ function, so e.g. like so:

 def __init__(self, name): super().__init__(self) self.name = name self.parent = None self.children = list() 

EDIT:
Added improvement suggested by @chepner.

Источник

Python Cookbook by

Get full access to Python Cookbook and 60K+ other titles, with a free 10-day trial of O’Reilly.

There are also live events, courses curated by job role, and more.

Getting All Members of a Class Hierarchy

Credit: Jürgen Hermann, Alex Martelli

Problem

You need to map all members of a class, including inherited members, into a dictionary of class attribute names.

Solution

Here is a solution that works portably and transparently on both new-style (Python 2.2) and classic classes with any Python version:

def all_members(aClass): try: # Try getting all relevant classes in method-resolution order mro = list(aClass._ _mro_ _) except AttributeError: # If a class has no _ _mro_ _, then it's a classic class def getmro(aClass, recurse): mro = [aClass] for base in aClass._ _bases_ _: mro.extend(recurse(base, recurse)) return mro mro = getmro(aClass, getmro) mro.reverse( ) members = <> for someClass in mro: members.update(vars(someClass)) return members

Discussion

The all_members function in this recipe creates a dictionary that includes each member (such as methods and data attributes) of a class with the name as the key and the class attribute value as the corresponding value. Here’s a usage example:

class Eggs: eggs = 'eggs' spam = None class Spam: spam = 'spam' class Breakfast(Spam, Eggs): eggs = 'scrambled' print all_members(Eggs) print all_members(Spam) print all_members(Breakfast)

And here’s the output of this example (note that the order in which each dictionary’s items are printed is arbitrary and may vary between Python interpreters):

After constructing the dictionary d with d=all_members(c) , you can use d for repeated introspection about class c . d.has_key(x) is the same as hasattr(c,x) , and d.get(x) is the same as getattr(c,x,None) , but it doesn’t repeat the dynamic search procedure each time. Apart from the order of its items, d.keys is like dir(c) if c is a new-style class (for which dir also returns the names of inherited attributes) but is richer and potentially more useful than dir(c) if c is a classic class (for which dir does not list inherited attributes, only attributes defined or overridden directly in class c itself).

The all_members function starts by getting a list of all relevant classes (the class itself and all of its bases, direct and indirect), in the order in which attributes are looked up, in the mro variable (MRO stands for method-resolution order). This happens immediately for a new-style class, since it exposes this information with its _ _mro_ _ attribute—we just need to build a list from it, since it is a tuple. If accessing _ _mro_ _ fails, we’re dealing with a classic class and must build mro up in a recursive way. We do that in the nested function getmro in the except clause. Note that we give getmro itself as an argument to facilitate recursion in older Python versions that did not support lexically nested scopes.

Once we have mro , we need to reverse it, because we build up our dictionary with the update method. When we call adict.update(anotherdict) , the entries in the two dictionaries adict and anotherdict are merged as the new contents of adict . In case of conflict (i.e., a key k is present in both dictionaries), the value used is anotherdict[k] , which overrides the previous value of adict[k] . Therefore, we must build our dictionary starting with the classes that are looked up last when Python is looking for an attribute. We move towards the classes that are looked up earlier to reproduce how overriding works with inheritance. The dictionaries we merge in this way are those given sequentially by the built-in function vars on each class. vars takes any object as its argument and returns a dictionary of the object’s attributes. Note that even for new-style classes in Python 2.2, vars does not consider inherited attributes, just the attributes defined or overridden directly in the object itself, as dir does only for classic classes.

See Also

Understanding method resolution order is a new challenge even for old Python hands. The best description is in Guido’s essay describing the unification of types and classes (http://www.python.org/2.2/descrintro.html#mro), which was refined somewhat in PEP 253 (http://www.python.org/peps/pep-0253.html).

Get Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Источник

Оцените статью