Python: Dynamically generating attributes from a list - python

I want to be able to dynamically generate attributes of a class from a list or dictionary. The idea is that I can define a list of attributes, and then be able to access those attributes using my_class.my_attribute
For example:
class Campaign(metaclass=MetaCampaign):
_LABELS = ['campaign_type', 'match_type', 'audience_type'] # <-- my list of attributes
for label in _LABELS:
setattr(cls, label, LabelDescriptor(label))
def __init__(self, campaign_protobuf, labels)
self._proto = campaign_protobuf
self._init_labels(labels_dict)
def _init_labels(self, labels_dict):
# magic...
This obviously won't work because cls doesn't exist, but I'd like:
my_campaign = Campaign(campaign, label_dict)
print(my_campaign.campaign_type)
to return the value campaign_type for the campaign. This is obviously a little complicated, as campaign_type is actually a Descriptor and does a bit of work to retrieve a value from a base Label object.
The Descriptor:
class DescriptorProperty(object):
def __init__(self):
self.data = WeakKeyDictionary()
def __set__(self, instance, value):
self.data[instance] = value
class LabelTypeDescriptor(DescriptorProperty):
"""A descriptor that returns the relevant metadata from the label"""
def __init__(self, pattern):
super(MetaTypeLabel, self).__init__()
self.cached_data = WeakKeyDictionary()
# Regex pattern to look in the label:
# r'label_type:ThingToReturn'
self.pattern = f"{pattern}:(.*)"
def __get__(self, instance, owner, refresh=False):
# In order to balance computational speed with memory usage, we cache label values
# when they are first accessed.
if self.cached_data.get(instance, None) is None or refresh:
ctype = re.search(self.pattern, self.data[instance].name) # <-- does a regex search on the label name (e.g. campaign_type:Primary)
if ctype is None:
ctype = False
else:
ctype = ctype.group(1)
self.cached_data[instance] = ctype
return self.cached_data[instance]
This enables me to easily access the value of a label, and if the label is of a type that I care about, it will return the relevant value, otherwise it will return False.
The Label Object:
class Label(Proto):
_FIELDS = ['id', 'name']
_PROTO_NAME = 'label'
# We define what labels can pull metadata directly through a property
campaign_type = LabelTypeDescriptor('campaign_type')
match_type = LabelTypeDescriptor('match_type')
audience_type = LabelTypeDescriptor('audience_type')
def __init__(self, proto, **kwargs):
self._proto = proto
self._set_default_property_values(self) # <-- the 'self' is intentional here, in the campaign object a label would be passed instead.
def _set_default_property_values(self, proto_wrapper):
props = [key for (key, obj) in self.__class__.__dict__.items() if isinstance(obj, DescriptorProperty)]
for prop in props:
setattr(self, prop, proto_wrapper)
So if I have a protobuf label object stored in my Label (which is basically just a wrapper) which looks like this:
resource_name: "customers/12345/labels/67890"
id {
value: 67890
}
name {
value: "campaign_type:Primary"
}
Then my_label.campaign_type would return Primary, and similarly my_label.match_type would return False
The reason being is that I'm creating a number of classes that are all labelled in the same way, and may have a lot of labels. Currently this all works as described, but I'd like to be able to define the attributes more dynamically as they all basically follow the same type of pattern. So instead of :
campaign_type = LabelTypeDescriptor('campaign_type')
match_type = LabelTypeDescriptor('match_type')
audience_type = LabelTypeDescriptor('audience_type')
... # (many more labels)
I simply have: _LABELS = ['campaign_type', 'match_type', 'audience_type', ... many more labels] and then have some loop that creates the attributes.
In turn I can cascade a similar approach through to my other classes, so that while a Campaign object may hold a Label object, I can access the value of the label simply by my_campaign.campaign_type. If the campaign does not have a label of the appropriate type, it will simply return False.

While cls does not exist when the class body is run, you can set the attributes by simply setting then in the dictionary returned by locals() inside the class body:
class Campaign(metaclass=MetaCampaign):
_LABELS = ['campaign_type', 'match_type', 'audience_type'] # <-- my list of attributes
for label in _LABELS:
locals()[label] = label, LabelDescriptor(label)
del label # so you don't get a spurious "label" attribute in your class
Other than that you can use a metaclass, yes, but also a __init_suclass__ on a base class. Less metaclasses mean less "moving parts" that can behave in strange ways in your system.
So, say your Proto class is the base for all others that need this feature:
class Proto:
def __init_subclass__(cls, **kwd):
super().__init_subclass__(**kwd)
for label in cls._LABELS:
setattr(cls, label, LabelDescriptor(label))
...
I had taken a look at your Descriptors and code there - if they ar already working, I'd say they are all right.
I can comment that it is more usual to store descriptor-related data in the instance's __dict__ itself, instead of creating the data and cached_datain the descriptor itself - so one don't need to care about weakrefs - but both approaches work (just this week, I had implemented a descriptor in this way, even though I usually go for the instance's __dict__)

You could define a classmethod that will initialize these attributes, and call this method after the class declaration:
class Campaign(metaclass=MetaCampaign):
_LABELS = ['campaign_type', 'match_type', 'audience_type'] # <-- my list of attributes
#classmethod
def _init_class(cls):
for label in cls._LABELS:
setattr(cls, label, LabelDescriptor(label))
# After the class has been declared, initialize the attributes
Campaign._init_class()

Related

Create multiple classes or multiple objects in Python?

I have the following problem and I need advice on how to solve it the best technically in Python. As I am new to programming I would like to have some advice.
So I will have the following object and they should store something. Here is an example:
object 1: cash dividends (they will have the following properties)
exdate (will store a list of dates)
recorddate (will store a list of dates)
paydate (will store a list of dates)
ISIN (will store a list of text)
object 2: stocksplits (they will have the following prpoerties)
stockplitratio (will be some ration)
exdate(list of dates)
...
I have tried to solve it like this:
class cashDividends(object):
def __init__(self, _gross,_net,_ISIN, _paydate, _exdate, _recorddate, _frequency, _type, _announceddate, _currency):
self.gross = _gross
self.net = _net
self.ISIN = _ISIN
self.paydate = _paydate
self.exdate = _exdate
self.recorddate = _recorddate
self.frequency = _frequency
self.type = _type
self.announceddate = _announceddate
self.currency = _currency
So if I have this I would have to create another class named stockplits and then define an __init__ function again.
However is there a way where I can have one class like "Corporate Actions" and then have stock splits and cashdividends in there ?
Sure you can! In python you can pass classes to other classes.
Here a simple example:
class A():
def __init__(self):
self.x = 0
class B():
def __init__(self):
self.x = 1
class Container():
def __init__(self, objects):
self.x = [obj.x for obj in objects]
a = A()
b = B()
c = Container([a,b])
c.x
[0,1]
If I understood correctly what you want is an object that has other objects from a class you created as property?
class CorporateActions(object):
def __init__(self, aCashDividend, aStockSplit):
self.cashDividend = aCashDividend
self.stockSplit = aStockSplit
myCashDividends = CashDividends(...) #corresponding parameters here
myStockSplit = StockSplit(...)
myCorporateActions = CorporateActions(myCashDividends, myStockSplit)
Strictly speaking this answer isn't an answer for the final question. However, it is a way to make your life slightly easier.
Consider creating a sort-of template class (I'm using this term loosely; there's no such thing in Python) that does the __init__ work for you. Like this:
class KwargAttrs():
def __init__(self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)
def _update(self, **kwargs):
args_dict = {k:(kwargs[k] if k in kwargs else self.__dict__[k]) for k in self.__dict__}
self.__dict__.update(args_dict)
This class uses every supplied keyword argument as an object attribute. Use it this way:
class CashDividends(KwargAttrs):
def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
# save the namespace before it gets polluted
super().__init__(**locals())
# work that might pollute local namespace goes here
# OPTIONAL: update the argument values in case they were modified:
super()._update(**locals())
Using a method like this, you don't have to go through the argument list and assign every single object attribute; it happens automatically.
We bookend everything you need to accomplish in the __init__ method with method calls to the parent-class via super(). We do this because locals() returns a dict every variable in the function's current namespace, so you need to 1.) capture that namespace before any other work pollutes it and 2.) update the namespace in case any work changes the argument values.
The call to update is optional, but the values of the supplied arguments will not be updated if something is done to them after the call to super().__init__() (that is, unless you change the values using setattr(self, 'argname, value)`, which is not a bad idea).
You can continue using this class like so:
class StockSplits(KwargAttrs):
def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
super().__init__(**locals())
As mentioned in the other answers you can create a container for our other classes, but you can even do that using this same template class:
class CorporateActions(KwargAttrs):
def __init__(self, stock_splits , cash_dividends):
super().__init__(**locals())
ca = CorporateActions(stock_splits = StockSplits(<arguments>), cash_dividends = CashDividends(<arguments>) )

Extract (not known beforehand) attributes from objects in a list

I have a class whose attributes are not known beforehand:
class Event():
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
and another one which is basically a list of objects Event:
class Collection(list):
def __init__(self):
self.members = []
def add(self,new):
try:
self.members.extend(new)
except TypeError:
self.members.append(new)
Let's say now that I define 3 objects Event:
a = Event(name="a",value=1)
b = Event(name="b",value=2)
c = Event(name="c",other=True)
And I create a Collection from them:
col = Collection()
col.add([a,b,c])
What I want is to be able to print out all the values of the objects in the list for a given attribute (if the attribute does not exist for an object, it should return None or any other pre-defined value). For example:
print col.name #should return ["a","b","c"]
print col.value #should return [1,2,None]
I have read the following answer: Extract list of attributes from list of objects in python
But that doesn't work here since the name of my attribute is not known by advance, and some might not even be defined. How should I define my class Collection(), or maybe even re-think everything to achieve my goal ?
This is a variation of "I want to create dynamic variable names". The solution here is the same: use a dictionary.
class Event(object):
def __init__(self, **kwargs):
self.attributes = dict(kwargs)
Your Collection class will need a custom __getattr__ method, so that it can look up values in its Event list instead.
class Collection(object):
# assume self.events is a list of Event objects
def __getattr__(self, name):
return [event.attributes.get(name) for event in self.events]
You could stick with your current implementation of Event, and have Collection look at event.__dict__ instead of event.attributes. I don't recall, though, if __dict__ might contain anything else besides the attributes you explicitly set. I'd err on the side of caution.
You can just override the __getattr__ method of the Collection class, which is called when an attribute is accessed. In order to access to unknown set of attributes you can use event.__dict__. So, a possible solution is like this:
def __getattr__(self, name):
return [m.__dict__.get(name) for m in self.members]

Generate a list of class members that preserves their definition order

I am trying to automatically create some SQL tables from the definition of some Python classes, I tried using dir() but since it returns a Python Dictionary, it's not ordered so the definition order of the class members is lost.
Reading on the internet I found the following here
class OrderedClass(type):
#classmethod
def __prepare__(metacls, name, bases, **kwds):
return collections.OrderedDict()
def __new__(cls, name, bases, namespace, **kwds):
result = type.__new__(cls, name, bases, dict(namespace))
result.members = tuple(namespace)
return result
class A(metaclass=OrderedClass):
def one(self): pass
def two(self): pass
def three(self): pass
def four(self): pass
>>> A.members
('__module__', 'one', 'two', 'three', 'four')
I successfuly implemented a copy of it, and it appears to be doing what it should except that it's only saving the methods in the members variable, and I need to have also the class member variables.
Question:
How could I get a list of the member variables preserving their definition order?, I don't care about class methods, and I am actually ignoring them.
Note: The reason why the order is important is because the tables will have constraints that reference some of the table columns, and they must go after defining the column, but they are appearing before.
Edit: This is a sample class in my real program
class SQLTable(type):
#classmethod
def __prepare__(metacls, name, bases, **kwds):
return OrderedDict()
def __new__(cls, name, bases, namespace, **kwds):
result = type.__new__(cls, name, bases, dict(namespace))
result.members = tuple(namespace)
return result
class AreaFisicoAmbiental(metaclass = SQLTable):
def __init__(self, persona, datos):
# edificacion
self.persona = persona
self.tipoEdificacion = datos[0]
self.tipoDeParedes = datos[1]
self.detallesTipoDeParedes = datos[2]
self.tipoDeTecho = datos[3]
self.detallesTipoDeTecho = datos[4]
self.tipoDePiso = datos[5]
self.detallesTipoDePiso = datos[6]
# ambientes
self.problemaDeInfraestructura = datos[7]
self.detallesProblemaDeInfraestructura = datos[9]
self.condicionDeTenencia = datos[10]
self.detallesCondicionDeTenencia = datos[11]
self.sala = toBool(datos[12])
self.comedor = toBool(datos[13])
self.baño = toBool(datos[14])
self.porche = toBool(datos[15])
self.patio = toBool(datos[16])
self.lavandero = toBool(datos[17])
self.habitaciones = toInt(datos[19])
# servicios básicos
self.aguasServidas = toBool(datos[21])
self.aguaPotable = toBool(datos[22])
self.luz = toBool(datos[23])
self.gas = datos[24]
self.internet = toBool(datos[25])
Doing
print(AreaFisicoAmbiental.members)
Outputs:
('__module__', '__qualname__', '__init__')
Variable names are in spanish because their names will be used as the table column names, and also as the labels for a web application that will be generated from the database structure.
I know that Django does something like this, but I already have my database inspector which does the opposite thing, so know I need a Django like functionality to use my generator.
Updated
As I commented, I think you're probably confusing instance attributes with class attributes and really want to keep track of the latter. Instance attributes are dynamic and can be added, changed, or removed at any time, so trying to do this with a metaclass like shown in your question won't work (and different instances may have a different group of them defined).
You may be able to keep track of their creation and deletion by overloading a couple of the class's special methods, namely __setattr__() and __delattr__() and storing their effects in a private data member which is an OrderedSet. Do so will keep track of what they are and preserve the order in which they were created.
Both of these methods will need to be careful not to operate upon the private data member itself.
That said, here's something illustrating such an implementation:
# -*- coding: iso-8859-1 -*-
# from http://code.activestate.com/recipes/576694
from orderedset import OrderedSet
class AreaFisicoAmbiental(object):
def __init__(self, persona, datos):
self._members = OrderedSet()
self.persona = persona
self.tipoEdificacion = datos[0]
self.tipoDeParedes = datos[1]
def __setattr__(self, name, value):
object.__setattr__(self, name, value)
if name != '_members':
self._members.add(name)
def __delattr__(self, name):
if name != '_members':
object.__delattr__(self, name)
self._members.discard(name)
def methodA(self, value1, value2): # add some members
self.attribute1 = value1
self.attribute2 = value2
def methodB(self):
del self.attribute1 # remove a member
if __name__ == '__main__':
a = AreaFisicoAmbiental('Martineau', ['de albañilería', 'vinilo'])
a.methodA('attribute1 will be deleted', 'but this one will be retained')
a.methodB() # deletes a.attribute1
a.attribute3 = 42 # add an attribute outside the class
print('current members of "a":')
for name in a._members:
print(' {}'.format(name))
Output:
current members of "a":
persona
tipoEdificacion
tipoDeParedes
attribute2
attribute3
A final note: It would be possible to create a metaclass that added these two methods automatically to client classes, which would make it easier to modify existing classes.
Maybe, python enum would be enough for the task. Indeed it supports stable order.
The basic implementation of DDL would look like this:
from enum import Enum
class Table1(Enum):
nombre = ''
edad = 0
sexo = True
...
then later you could do:
for prop in Table1:
print(prop)
this gives you
Table1.nombre
Table1.edad
Table1.sexo
if you need to construct a proper table definition you could use Table1.<field>.value:
>>> print(type(Table1.nombre.value))
<class 'str'>
>>> print(type(Table1.edad.value))
<class 'int'>
and so on. Using this technique you could even link some tables to others thus constructing a complete definition of a whole set of tables and their relationships.
As for data objects (e.g. a row in a table, or a row of a query results), here I think you don't any own ordering, you just need to maintain a link to a corresponding table class (from which the order can be restored, however I don't think it's such a requested option). So these classes could look like this:
class Table1Row(object):
_table = Table1
__slots__ = tuple(k.name for k Table1)
...
or simply
class ASpecificQueryResults(object):
__slots__ = (Table1.nombre.name, Table2.empresa.name,...)
probably you need a factory which would build row classes based on the query results and/or table definitions.
Edit probably the idea with __slots__ in *Row classes requires some more polish but this heavily depends on your actual needs.
P.S. Perhaps 'Table1.sexo' also should be an enum in our complicated times ;)

Set and Get #property method in Python by string variable

Currently I have a generalized function where you can pass in an attribute name and a class (it would also work with specific object instances, but I am using classes), and the function will look up and operate on that attribute by calling
getattr(model_class, model_attribute)
and it will modify the attribute by calling (on an object instance this time)
settattr(model_obj, key, value)
However, I have a class where we have an #property method defined instead of a simple attribute, and setattr does not work. How do I dynamically get the #property based on a string name for that property method?
Perhaps I could use __dict__ but that seems dirty and not as safe.
Edit: example code
The generalized function
def process_general(mapping, map_keys, model_class, filter_fn, op_mode=op_modes.UPDATE):
"""
Creates or updates a general table object based on a config dictionary.
`mapping`: a configuration dictionary, specifying info about the table row value
`map_keys`: keys in the mapping that we use for the ORM object
`model_class`: the ORM model class we use the config data in
`op_mode`: the kind of operation we want to perform (delete, update, add, etc.)
Note that relationships between model objects must be defined and connected
outside of this function.
"""
# We construct a dictionary containing the values we need to set
arg_dict = make_keyword_args(map_keys, mapping)
# if we are updating, then we must first check if the item exists
# already
if (op_mode == op_modes.UPDATE):
# Find all rows that match by the unique token.
# It should only be one, but we will process all of them if it is the
# case that we didn't stick to the uniqueness requirement.
matches = filter_fn()
# Keep track of the length of the iterator so we know if we need to add
# a new row
num_results = 0
for match in matches:
# and we set all of the object attributes based on the dictionary
set_attrs_from_dict(match, arg_dict)
model_obj = match
num_results += 1
# We have found no matches, so just add a new row
if (num_results < 1):
model_obj = model_class(**arg_dict)
return model_obj
# TODO add support for other modes. This here defaults to add
else:
return model_class(**arg_dict)
An example class passed in:
class Dataset(db.Model, UserContribMixin):
# A list of filters for the dataset. It can be built into the dataset filter form dict
# in get_filter_form. It's also useful for searching.
filters = db.relationship('DatasetFilter', backref='dataset')
# private, and retrieved from the #property = select
_fact_select = db.relationship('DatasetFactSelect', order_by='DatasetFactSelect.order')
#property
def fact_select(self):
"""
FIXME: What is this used for?
Appears to be a list of strings used to select (something) from the
fact model in the star dataset interface.
:return: List of strings used to select from the fact model
:rtype: list
"""
# these should be in proper order from the relationship order_by clause
sels = [sel.fact_select for sel in self._fact_select]
return sels
Calling getattr(model_class, model_attribute) will return the property object that model_attribute refers to. I'm assuming you already know this and are trying to access the value of the property object.
class A(object):
def __init__(self):
self._myprop = "Hello"
#property
def myprop(self):
return self._myprop
#myprop.setter
def myprop(self, v):
self._myprop = v
prop = getattr(A, "myprop")
print prop
# <property object at 0x7fe1b595a2b8>
Now that we have obtained the property object from the class we want to access its value. Properties have three methods fget, fset, and fdel that provide access to the getter, settter, and deleter methods defined for that property.
Since myprop is an instance method, we'll have to create an instance so we can call it.
print prop.fget
# <function myprop at 0x7fe1b595d5f0>
print prop.fset
# <function myprop at 0x7fe1b595d668>
print prop.fdel # We never defined a deleter method
# None
a = A()
print prop.fget(a)
# Hello
For the most general case follow this example:
class Foo(object):
#property
def bar(self):
return self._spam
#bar.setter
def bar(self, v):
self._spam = v
foo = Foo()
# prop = foo.bar.fset('Aaaah') # will raise an error
# if you wanna access the setter do:
type(foo).bar.fset(foo, 'Aaaah')
print(foo.bar)

How to implement property() with dynamic name (in python)

I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:
class SingleParameter(object):
def __init__(self, name, default_value=0, unit='not specified'):
self.name = name
self.default_value = default_value
self.unit = unit
self.set(default_value)
def get(self):
return self._v
def set(self, value):
self._v = value
v = property(fget=get, fset=set, doc='value of parameter')
par1 = SingleParameter(name='par1', default_value=10, unit='mV')
par2 = SingleParameter(name='par2', default_value=20, unit='mA')
# par1 and par2 I can access perfectly via 'p1.v = ...'
# or get its value with 'p1.v'
class Collection(object):
def __init__(self):
self.dict = {}
def __getitem__(self, name):
return self.dict[name] # get the whole object
# to get the value instead:
# return self.dict[name].v
def add(self, parameter):
self.dict[parameter.name] = parameter
# now comes the part that I don't know how to implement with property():
# It shoule be something like
# self.__dict__[parameter.name] = property(...) ?
col = Collection()
col.add(par1)
col.add(par2)
col['par1'] # gives the whole object
# Now here is what I would like to get:
# col.par1 -> should result like col['par1'].v
# col.par1 = 5 -> should result like col['par1'].v = 5
Other questions that I put to understand property():
Why do managed attributes just work for class attributes and not for instance attributes in python?
How can I assign a new class attribute via __dict__ in python?
Look at built-in functions getattr and setattr. You'll probably be a lot happier.
Using the same get/set functions for both classes forces you into an ugly hack with the argument list. Very sketchy, this is how I would do it:
In class SingleParameter, define get and set as usual:
def get(self):
return self._s
def set(self, value):
self._s = value
In class Collection, you cannot know the information until you create the property, so you define the metaset/metaget function and particularize them only later with a lambda function:
def metaget(self, par):
return par.s
def metaset(self, value, par):
par.s = value
def add(self, par):
self[par.name] = par
setattr(Collection, par.name,
property(
fget=lambda x : Collection.metaget(x, par),
fset=lambda x, y : Collection.metaset(x,y, par))
Properties are meant to dynamically evaluate attributes or to make them read-only. What you need is customizing attribute access. __getattr__ and __setattr__ do that really fine, and there's also __getattribute__ if __getattr__ is not enough.
See Python docs on customizing attribute access for details.
Have you looked at the traits package? It seems that you are reinventing the wheel here with your parameter classes. Traits also have additional features that might be useful for your type of application (incidently I know a person that happily uses traits in neural simulations).
Now I implemented a solution with set-/getattr:
class Collection(object):
...
def __setattr__(self, name, value):
if 'dict' in self.__dict__:
if name in self.dict:
self[name].v = value
else:
self.__dict__[name] = value
def __getattr__(self, name):
return self[name].v
There is one thing I quite don't like that much: The attributes are not in the __dict__. And if I have them there as well I would have a copy of the value - which can be dangerous...
Finally I succeded to implement the classes with property(). Thanks a lot for the advice. It took me quite a bit to work it out - but I can promise you that this exercise helps you to understand better pythons OOP.
I implemented it also with __getattr__ and __setattr__ but still don't know the advantages and disadvantages to the property-solution. But this seems to be worth another question. The property-solutions seems to be quit clean.
So here is the code:
class SingleParameter(object):
def __init__(self, name, default_value=0, unit='not specified'):
self.name = name
self.default_value = default_value
self.unit = unit
self.set(default_value)
def get(*args):
self = args[0]
print "get(): "
print args
return self._v
def set(*args):
print "set(): "
print args
self = args[0]
value = args[-1]
self._v = value
v = property(fget=get, fset=set, doc='value of parameter')
class Collection(dict):
# inheriting from dict saves the methods: __getitem__ and __init__
def add(self, par):
self[par.name] = par
# Now here comes the tricky part.
# (Note: this property call the get() and set() methods with one
# more argument than the property of SingleParameter)
setattr(Collection, par.name,
property(fget=par.get, fset=par.set))
# Applying the classes:
par1 = SingleParameter(name='par1', default_value=10, unit='mV')
par2 = SingleParameter(name='par2', default_value=20, unit='mA')
col = Collection()
col.add(par1)
col.add(par2)
# Setting parameter values:
par1.v = 13
col.par1 = 14
# Getting parameter values:
par1.v
col.par1
# checking identity:
par1.v is col.par1
# to access the whole object:
col['par1']
As I am new I am not sure how to move on:
how to treat follow up questions (like this itself):
get() is seems to be called twice - why?
oop-design: property vs. "__getattr__ & __setattr__" - when should I use what?
is it rude to check the own answer to the own question as accepted?
is it recommended to rename the title in order to put correlated questions or questions elaborated with the same example into the same context?
Other questions that I put to understand property():
Why do managed attributes just work for class attributes and not for instance attributes in python?
How can I assign a new class attribute via __dict__ in python?
I have a class that does something similar, but I did the following in the collection object:
setattr(self, par.name, par.v)

Categories