If you want to iterate over the class, you have to define a metaclass which supports iteration.
x.py:
class it(type):
def __iter__(self):
# Wanna iterate over a class? Then ask that class for iterator.
return self.classiter()
class Foo:
__metaclass__ = it # We need that meta class...
by_id = {} # Store the stuff here...
def __init__(self, id): # new isntance of class
self.id = id # do we need that?
self.by_id[id] = self # register istance
@classmethod
def classiter(cls): # iterate over class by giving all instances which have been instantiated
return iter(cls.by_id.values())
if __name__ == '__main__':
a = Foo(123)
print list(Foo)
del a
print list(Foo)
As you can see in the end, deleting an instance will not have any effect on the object itself, because it stays in the by_id dict. You can cope with that using weakrefs when you
import weakref
and then do
by_id = weakref.WeakValueDictionary()
. This way the values will only kept as long as there is a "strong" reference keeping it, such as a in this case. After del a, there are only weak references pointing to the object, so they can be gc'ed.
Due to the warning concerning WeakValueDictionary()s, I suggest to use the following:
[...]
self.by_id[id] = weakref.ref(self)
[...]
@classmethod
def classiter(cls):
# return all class instances which are still alive according to their weakref pointing to them
return (i for i in (i() for i in cls.by_id.values()) if i is not None)
Looks a bit complicated, but makes sure that you get the objects and not a weakref object.
If you want to iterate over the class, you have to define a metaclass which supports iteration.
x.py:
class it(type):
def __iter__(self):
# Wanna iterate over a class? Then ask that class for iterator.
return self.classiter()
class Foo:
__metaclass__ = it # We need that meta class...
by_id = {} # Store the stuff here...
def __init__(self, id): # new isntance of class
self.id = id # do we need that?
self.by_id[id] = self # register istance
@classmethod
def classiter(cls): # iterate over class by giving all instances which have been instantiated
return iter(cls.by_id.values())
if __name__ == '__main__':
a = Foo(123)
print list(Foo)
del a
print list(Foo)
As you can see in the end, deleting an instance will not have any effect on the object itself, because it stays in the by_id dict. You can cope with that using weakrefs when you
import weakref
and then do
by_id = weakref.WeakValueDictionary()
. This way the values will only kept as long as there is a "strong" reference keeping it, such as a in this case. After del a, there are only weak references pointing to the object, so they can be gc'ed.
Due to the warning concerning WeakValueDictionary()s, I suggest to use the following:
[...]
self.by_id[id] = weakref.ref(self)
[...]
@classmethod
def classiter(cls):
# return all class instances which are still alive according to their weakref pointing to them
return (i for i in (i() for i in cls.by_id.values()) if i is not None)
Looks a bit complicated, but makes sure that you get the objects and not a weakref object.
Magic methods are always looked up on the class, so adding __iter__ to the class won't make it iterable. However the class is an instance of its metaclass, so the metaclass is the correct place to define the __iter__ method.
class FooMeta(type):
def __iter__(self):
return self.by_id.iteritems()
class Foo:
__metaclass__ = FooMeta
...
Hi @Ronald Rex , Welcome to Microsoft Q&A,
Are there any preconditions?
To iterate over all properties of a POCO class, you can use reflection. In C#, you can use the "Type" class to get information about the properties of an object type.
First use GetType() to get the type of the OrderPoco object. Then, use "GetProperties()" to retrieve an array of "PropertyInfo" objects that represent the class properties. Finally, iterate through the property information and use GetValue() to access the property's values and print them to the console.
Public properties available only for POCO classes. If you have private or protected properties, you will need to modify your code accordingly. In addition, using reflection may reduce performance and needs to be used with caution.
using System;
using System.Reflection;
class Program
{
static void Main()
{
var o = new OrderPoco()
{
OrderID = 1,
CustomerID = "ABCDE",
Shipper = 3
};
// Get the type of the object
Type type = o.GetType();
// Get all public properties of the object's type
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
// Get the name and value of each property
string propertyName = property.Name;
object propertyValue = property.GetValue(o);
Console.WriteLine($"{propertyName}: {propertyValue}");
}
}
}
class OrderPoco
{
public int OrderID { get; set; }
public string CustomerID { get; set; }
public int Shipper { get; set; }
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
What is the purpose of doing this?
You can iterate as shown below to get property names.
foreach (PropertyInfo p in typeof(OrderPoco).GetProperties())
{
string propertyName = p.Name;
}
And use the following method to get values. But still does not get what you want yet I see if as viable.
Is there a way I can iterate over the attributes of a class?
How to iterate through class properties of a class? - Questions & Answers - Unity Discussions
loops - How to iterate through class instance - Stack Overflow
iterate through classes on same element - javascript
You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.
For a hint, you could possibly do something like:
Record record = new Record();
PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
property.SetValue(record, value);
}
Where value is the value you're wanting to write in (so from your resultItems array).
I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo
list was coming as empty. So, I tried the following and it worked for me.
Type type = typeof(Record);
FieldInfo[] properties = type.GetFields();
foreach (FieldInfo property in properties) {
Debug.LogError(property.Name);
}
I am fairly new to python, and have been working on creating 'Worldbuilding' app, That lets the user perform CRUD operations on a database from a UI.
I am using SQLAlchemy's ORM to model my data structure as following:
class Character(base):
__tablename__ = "Character"
id = Column(Integer, primary_key=True)
name = Column(String)
home_town = Column(String)
age = Column(Integer)
def get_columns(self):
return ["id", "name", "home_town", "age"]
def get_values(self):
return [self.id, self.name, self.home_town, self.age]
example = Character(name="Bilbo", home_town="The Shire", age=111)I want to get a list of my 'columns' (attributes) and the values for each 'row' (Instance).
I have written two 'get_' methods for this, but they feel very arbitrary and undynamic (for instance, adding new attributes would require me to edit the methods as well).
The closest thing I have found so far is the class's __dict__ attribute, but I ideally want my output as a list if possible.
I would greatly appreciate any help :)
In JavaScript, to get the list of classes, you can use
.className.split(' '), returns anArray- (HTML5)
.classList, returns aDOMTokenList
In jQuery, you can use .prop() to get className or classList properties.
To iterate them, you can use:
- A
forloop, e.g.for(var i=0; i<classes.length; ++i) - (ES6) A
for...ofloop, e.g.for(var cl of classes). - (ES5)
forEach, only for arrays, e.g.classes.forEach(fn) - (jQuery)
$.each, e.g.$.each(classes, fn)
If you use classList but want to iterate using forEach, you can convert the DOMTokenList into an Array using
[].slice.call(classes)- (ES6)
Array.from(classes)
First you need to get an string that contains the classes with:
$('div').attr('class');
and split it with blank spaces to get an array with:
$('div).attr('class').split(' ');
and then use that array as the first argument to an $.each function where the index and the value can help you to handle it independently
$.each($('div').attr('class').split(' '), function(index, value) {
console.log('Class name ' + value);
});
Hi,
So i have a dictionary which contains instances of several classes, which kinda looks like
d = {"key1" : object,... }where object can be of type root.class1.class2.abc.class3, root.class1.class2.def.class4 and so on. And these objects have additional variables like
Obj._name = "some_name";
Obj._args = {key1: value, key2: class_object}What I have to do is look into all these objects and find some variable names and get their values. So input request could look like
class_type = "abc.class3" param_name = "_args.key2"
Right now I'm doing like
if class_type in str(type(obj)): blah blah
to locate class_type of the object and then use obj.get('some_name') if it's a dict, obj.getattr('some_name') if the type is dict with an occasional if 'some_name in vars(obj)` to check if name exists in class object.
The code works but it's a mess as there are too many isinatance calls and kinda long because everywhere I'm handing inputs based on their type. It looks like lot of straws taped together and I feel like the code is gonna break if some unexpected input is given.
Is there some library available that can recursively look inside an objects/sub-objects/sub-sub-objects (list/dict/class) and tell me if some name exists and it's value.
Right now I don't even know what query to type in google to search for such a library. If you can tell me some keywords to make search queries, even that would help. My poorly formed search queries are giving me stuff about iterating through lists or dicts
According to MDN, the way to retrieve an item from a NodeList is:
nodeItem = nodeList.item(index)
Thus:
const slides = document.getElementsByClassName("slide");
for (let i = 0; i < slides.length; i++) {
Distribute(slides.item(i));
}
I haven't tried this myself (the normal for loop has always worked for me), but give it a shot.
If you use the new querySelectorAll you can call forEach directly.
document.querySelectorAll('.edit').forEach(function(button) {
// Now do something with my button
});
Per the comment below. nodeLists do not have a forEach function.
If using this with babel you can add Array.from and it will convert non node lists to a forEach array. Array.from does not work natively in browsers below and including IE 11.
Array.from(document.querySelectorAll('.edit')).forEach(function(button) {
// Now do something with my button
});
At our meetup last night I discovered another way to handle node lists not having forEach
[...document.querySelectorAll('.edit')].forEach(function(button) {
// Now do something with my button
});
Browser Support for [...]
Showing as Node List

Showing as Array

You put all your Moons and Planets in a list.
for item in moons_planets_list:
if item.name == user_input:
#Do sth
Ordinarily, taking note of all instances of a class is not done automatically by Python or other languages.
However, you can do that by adding code in the __init__ method to register each instance as it is created in a "registry"of your choice.
This "registry" is any data structure which will track your instances - a simple dictionary can be enough for most cases. You can then just keep this dictionary at the module level, or as a class attribute: an attribute that is present on the class and shared across all instances.
If one is not doing some "production level code" which would have to handle all sorts of random events and misuses (for example, if one creates a Planet with a name that is already registered), the code can be quite simple.
Since the code would be common across Planets and Moons, it is a case for using class inheritance, and share the common functionality, without the functionality getting in the way of what you want to handle in Planets
class Registerable:
registry = {}
def __init__(self, name):
cls = self.__class__ # optional for readability
cls.registry[name] = self
super().__init__()
class Planets(Registerable):
registry = {}
def __init__(self, name, radius, sgp, soi, atmo_height, moons=()):
super().__init__(name)
self.name = name
self.radius = radius
self.sgp = sgp
self.soi = soi
self.atmo_height = atmo_height
self.moons = moons
...
class Moons(Planeys):
registry = {} # each class have to declare its own registry, otherwise they are all shared with the base class
And then you can iterate on your instances using Planets.registry and Moons.registry as normal Python dictionaries.