Terminology of Class “attribute” vs “member” vs “variable” vs “field” [closed]

Based on the variety of answers, Class “attributes”, “fields”, and “variables” are used relatively interchangeably but have nuanced distinctions that vary from person to person. As such, probably best to lump them together and not rely on the nuances. There’s consensus that a Class “member” includes methods as well as data, so it is distinct … Read more

Dynamically add fields to dataclass objects

You could use make_dataclass to create X on the fly: X = make_dataclass(‘X’, [(‘i’, int), (‘s’, str)]) x = X(i=42, s=”text”) asdict(x) # {‘i’: 42, ‘s’: ‘text’} Or as a derived class: @dataclass class X: i: int x = X(i=42) x.__class__ = make_dataclass(‘Y’, fields=[(‘s’, str)], bases=(X,)) x.s=”text” asdict(x) # {‘i’: 42, ‘s’: ‘text’}

How can I define a list field in django rest framework?

There is also the ListField in django rest framework, see http://www.django-rest-framework.org/api-guide/fields/#listfield wtih the examples: scores = serializers.ListField( child=serializers.IntegerField(min_value=0, max_value=100) ) and (other notation): class StringListField(serializers.ListField): child = serializers.CharField() this seems simpler (maybe this class is added later than the accepted anwser, but seems good to add this option anyway) By the way, it’s added since … Read more

Java: How can I access a class’s field by a name stored in a variable?

You have to use reflection: Use Class.getField() to get a Field reference. If it’s not public you’ll need to call Class.getDeclaredField() instead Use AccessibleObject.setAccessible to gain access to the field if it’s not public Use Field.set() to set the value, or one of the similarly-named methods if it’s a primitive Here’s an example which deals … Read more

Any reason to use auto-implemented properties over manual implemented properties?

It doesn’t grant you anything extra beyond being concise. If you prefer the more verbose syntax, then by all means, use that. One advantage to using auto props is that it can potentially save you from making a silly coding mistake such as accidentally assigning the wrong private variable to a property. Trust me, I’ve … Read more

How to get the json field names of a struct in golang?

You use the StructTag type to get the tags. The documentation I linked has examples, look them up, but your code could be something like func (b example) PrintFields() { val := reflect.ValueOf(b) for i := 0; i < val.Type().NumField(); i++ { fmt.Println(val.Type().Field(i).Tag.Get(“json”)) } } NOTE The json tag format supports more than just field … Read more

tech