How to List All Variables of Class

How to list all Variables of Class

Your question isn't perfectly clear. It sounds like you want the values of the fields for a given instance of your class:

var fieldValues = foo.GetType()
.GetFields()
.Select(field => field.GetValue(foo))
.ToList();

Note that fieldValues is List<object>. Here, foo is an existing instance of your class.

If you want public and non-public fields, you need to change the binding flags via

var bindingFlags = BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public;
var fieldValues = foo.GetType()
.GetFields(bindingFlags)
.Select(field => field.GetValue(foo))
.ToList();

If you merely want the names:

var fieldNames = typeof(Foo).GetFields()
.Select(field => field.Name)
.ToList();

Here, Foo is the name of your class.

Get all variable names in a class

Field[] fields = YourClassName.class.getFields();

returns an array of all public variables of the class.

getFields() return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields(), and filter the public ones with the following Modifier approach:

Modifier.isPublic(field.getModifiers());

The YourClassName.class literal actually represents an object of type java.lang.Class. Check its docs for more interesting reflection methods.

The Field class above is java.lang.reflect.Field. You may take a look at the whole java.lang.reflect package.

looping over all member variables of a class in python

dir(obj)

gives you all attributes of the object.
You need to filter out the members from methods etc yourself:

class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False

example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members

Will give you:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']

Print all variables in a class? - Python

print db['han'].__dict__

How to get all values of variables in class?

There are two ways. This is a straight answer to your question:

class Foo:
pass

class Bar:
x: int = 1
y: str = 'hello'
z: Foo = Foo()

@classmethod
def get_all(cls):
xs = []
for name, value in vars(cls).items():
if not (name.startswith('__') or isinstance(value, classmethod)):
xs.append(value)
return xs

This is what I suggest:

from dataclasses import dataclass, fields

class Foo:
pass

@dataclass
class Bar:
x: int = 1
y: str = 'hello'
z: Foo = Foo()

@classmethod
def get_defaults(cls):
return [f.default for f in fields(cls)]

@classmethod
def get_all(cls):
return [getattr(cls, f.name) for f in fields(cls)]

results:

Bar.get_defaults() == Bar.get_all()
# True -> [1, 'hello', __main__.Foo]

Bar.x = 10
Bar.get_defaults() == Bar.get_all()
# False -> [1, 'hello', __main__.Foo] != [10, 'hello', __main__.Foo]

How to list all Variables of a class in swift

How you can do it in Swift 3.0 recursively:

import Foundation

class FirstClass {
var name = ""
var last_name = ""
var age = 0
var other = "abc"

func listPropertiesWithValues(reflect: Mirror? = nil) {
let mirror = reflect ?? Mirror(reflecting: self)
if mirror.superclassMirror != nil {
self.listPropertiesWithValues(reflect: mirror.superclassMirror)
}

for (index, attr) in mirror.children.enumerated() {
if let property_name = attr.label {
//You can represent the results however you want here!!!
print("\(mirror.description) \(index): \(property_name) = \(attr.value)")
}
}
}

}

class SecondClass: FirstClass {
var yetAnother = "YetAnother"
}

var second = SecondClass()
second.name = "Name"
second.last_name = "Last Name"
second.age = 20

second.listPropertiesWithValues()

results:

Mirror for FirstClass 0: name = Name
Mirror for FirstClass 1: last_name = Last Name
Mirror for FirstClass 2: age = 20
Mirror for FirstClass 3: other = abc
Mirror for SecondClass 0: yetAnother = YetAnother

Return all class variable values from a Python Class

In this case, you can enumerate all the attributes of the class that are uppercase; I'd use the vars() function to access the class namespace:

@classmethod
def all(cls):
return [value for name, value in vars(cls).items() if name.isupper()]

Demo:

>>> class AwsRegion():
... '''
... Class to define AWS Regions
... '''
... OHIO = 'us-east-2'
... NORTH_VIRGINIA = 'us-east-1'
... NORTH_CALIFORNIA = 'us-west-1'
... OREGON = 'us-west-2'
... MUMBAI = 'ap-south-1'
... SEOUL = 'ap-northeast-2'
... SINGAPORE = 'ap-southeast-1'
... SYDNEY = 'ap-southeast-2'
... TOKYO = 'ap-northeast-1'
... FRANKFURT = 'eu-central-1'
... IRELAND = 'eu-west-1'
... LONDON = 'eu-west-2'
... SAO_PAULO = 'sa-east-1'
... @classmethod
... def all(cls):
... return [value for name, value in vars(cls).items() if name.isupper()]
...
>>> AwsRegion.all()
['us-east-2', 'us-east-1', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'sa-east-1']

How to get a list of variables in a class in C#

You can use reflection.

Example:

class Foo {
public int A {get;set;}
public string B {get;set;}
}

...

Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}

From here: How to get the list of properties of a class?

Properties have attributes (properties) CanRead and CanWrite, which you may be interested in.

Documentation: http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx

Your question is a little vague, though. This may not be the best solution... depends heavily on what you're doing.

Is there a way to get to all variables of a certain type in a class?

Your code "compiles" to this:

var MyClass = (function () {
function MyClass() {
}
return MyClass;
}());

with nothing in there as you can see... however if you initialize your properties it will result some like this:

source TS:

class MyClass {
myNum1: number = 0;
myNum2: number = 0;
myNum3: number = 0;
myString: string = "";
myBoolean: boolean = false;
}

result JS:

var MyClass = (function () {
function MyClass() {
this.myNum1 = 0;
this.myNum2 = 0;
this.myNum3 = 0;
this.myString = "";
this.myBoolean = false;
}
return MyClass;
}());

then you can check instance properties:

var instance = new MyClass();
Object.keys(instance) //["myNum1", "myNum2", "myNum3", "myString", "myBoolean"]
instance["myNum1"] // 0

with that in mind you can filter the properties that you need:

var numerics = Object.keys(instance).map(k => instance[k]).filter(v => v.constructor === Number)
console.log(numerics) //[0, 0, 0]


Related Topics



Leave a reply



Submit