473,385 Members | 1,893 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

how to add property "dynamically"?

hello,

i need to add properties to instances dynamically during run time.
this is because their names are determined by the database contents.
so far i found a way to add methods on demand:

class A(object) :
def __getattr__(self, name) :
if name == 'test' :
def f() : return 'test'
setattr(self, name, f)
return f
else :
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))

this seems to work and i can invoke method test() on an object. it
would be nice to have it as property though. so i tried:

class A(object) :
def __getattr__(self, name) :
if name == 'test' :
def f() : return 'test'
setattr(self, name, property(f))
return f
else :
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))

but this does not work, instance.test returns a callable but does not
call it.

i am not an expert in python, would someone please tell me what i am
doing wrong?

thanks
konstantin
Aug 16 '08 #1
5 14546
akonsu wrote:
i am not an expert in python, would someone please tell me what i am
doing wrong?
You can't add properties to an instance. They must be specified on the
type (aka new style class). Descriptors and magic methods are only
looked up on classes for various reasons - mostly performance reasons.
Old style classes behave differently but properties don't work with old
style classes.

You can archive the same behavior by hooking into __getattr__,
__setattr__ and __delattr__. Mind the speed penelty, though!

Christian

Aug 17 '08 #2
akonsu wrote:
hello,

i need to add properties to instances dynamically during run time.
this is because their names are determined by the database contents.
so far i found a way to add methods on demand:

class A(object) :
def __getattr__(self, name) :
if name == 'test' :
def f() : return 'test'
setattr(self, name, f)
return f
else :
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))

this seems to work and i can invoke method test() on an object. it
would be nice to have it as property though. so i tried:

class A(object) :
def __getattr__(self, name) :
if name == 'test' :
def f() : return 'test'
setattr(self, name, property(f))
return f
else :
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))

but this does not work, instance.test returns a callable but does not
call it.

i am not an expert in python, would someone please tell me what i am
doing wrong?

thanks
konstantin
Are you sure you can't get by by adding attributes to the instance that hold the
values that the property would return?

class A(object):
def __init__(self, dbvaluedict):
self.__dict__.update(dbvaluedict)

>>dbvaluedict = dict('test': 'test')
a = A(dbvaluedict)
print a.test
test

If this doesn't help. You might want to start at the beginning and explain what
it is you are trying to accomplish. What you are trying to do is very unusual.

-Larry
Aug 17 '08 #3
On Aug 17, 5:09 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
akonsu a écrit :hello,
i need to add properties to instances dynamically during run time.
this is because their names are determined by the database contents.
so far i found a way to add methods on demand:
class A(object) :
def __getattr__(self, name) :
if name == 'test' :
def f() : return 'test'
setattr(self, name, f)
return f
else :
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))
this seems to work and i can invoke method test() on an object.

Nope. This adds per-instance *function* attributes - not *methods*.

class A(object) :
def __getattr__(self, name) :
if name == 'test' :
def f(self) :
return "%s.test" % self
setattr(self, name, f)
return f
else :
raise AttributeError(
"'%s' object has no attribute '%s'" \
% (self.__class__.__name__, name)
)

a = A()
a.test()
=Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 1 argument (0 given)

To add methods on a per-instance basis, you have to manually invoke the
descriptor protocol's implementation of function objects:

class A(object) :
def __getattr__(self, name) :
if name == 'test' :
def f(self) :
return "%s.test" % self
m = f.__get__(self, type(self))
setattr(self, name, m)
return m
else :
raise AttributeError(
"'%s' object has no attribute '%s'" \
% (self.__class__.__name__, name)
)
it
would be nice to have it as property though. so i tried:
class A(object) :
def __getattr__(self, name) :
if name == 'test' :
def f() : return 'test'
setattr(self, name, property(f))
return f
else :
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))
but this does not work, instance.test returns a callable but does not
call it.

Properties must be class attributes. The only way (the only way I know)
to get them to work as instance-attributes is to overload
__getattribute__, which is tricky and may have pretty bad impact on
lookup perfs - and ruins the whole point of using properties FWIW.
i am not an expert in python, would someone please tell me what i am
doing wrong?

Wrong solution to your problem, I'd say. Let's start again:

"""
i need to add properties to instances dynamically during run time.
this is because their names are determined by the database contents.
"""

Care to elaborate ? I may be wrong, but I suspect you're trying to roll
your own python/database mapper. If so, there are quite a couple Python
ORMs around. Else, please tell us more.
I posted this to another thread, but...
You can dynamically add properties (or anything else) to a CLASS just
before returning the
instance using __new__():

class AClass(object):
def __new__(cls):
setattr(cls,"propName", property(fget = ...,
fset = ...,
fdel = ...,
doc = ...) )

obj = super(AClass, cls).__new__(cls)
return obj
- Rafe
Aug 19 '08 #4
En Tue, 19 Aug 2008 15:02:29 -0300, Rafe <ra*******@gmail.comescribió:
On Aug 17, 5:09 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
>akonsu a écrit :hello,
i need to add properties to instances dynamically during run time.

Properties must be class attributes. The only way (the only way I know)
to get them to work as instance-attributes is to overload
__getattribute__, which is tricky and may have pretty bad impact on
lookup perfs - and ruins the whole point of using properties FWIW.

You can dynamically add properties (or anything else) to a CLASS just
before returning the
instance using __new__():

class AClass(object):
def __new__(cls):
setattr(cls,"propName", property(fget = ...,
fset = ...,
fdel = ...,
doc = ...) )

obj = super(AClass, cls).__new__(cls)
return obj
If you modify the class, this makes the property available to all existing
instances, not just the one being created. Any previous property of the
same name is overriden too.

--
Gabriel Genellina

Aug 20 '08 #5
Rafe a écrit :
(snip)
I posted this to another thread, but...
And I answered there, explaining why it's not a proper solution.
http://groups.google.com/group/comp....51a8614a58082#
(snip about using __new__ to add class attributes, cf above link for more)
Aug 20 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Action | last post by:
Let's say class parent class B : parent class C : parent ....etc. (may add later......so I don't know how many classes will there...) I wanna to let the user type in the class name and...
0
by: tommy | last post by:
hello everybody, i haved read a few articles about, how to create controls in asp.net dynamically! i have tested it -- all works fine.... but....now it comes--> HOW create controls...
3
by: Ahmed Ayoub | last post by:
i forgot how to create Textboxes & Label Dynamically. Meaning, i want to make them .. initialize their position .. and view them and interact with them.
9
by: Anubhav Jain | last post by:
Hi, I am having few .net source files(.cs or .vb) and I want to dynamically generate the corresponding .net project file(.csproj or .vbproj) for them without using visual studio.So that I could...
13
by: eman1000 | last post by:
I was recently looking at the prototype library (http://prototype.conio.net/) and I noticed the author used the following syntax: Object.extend(MyObj.prototype, { my_meth1: function(){},...
2
by: loga123 | last post by:
Hi All, I am new to .net. I am creating a text box in a "button1" "click event" dynamically based on user input. Name of the text box and ID of the text box contro are set dynamically in the...
669
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Languageâ€, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic...
2
by: Yarik | last post by:
Hello, I am not sure the subject of my post adequately describes the problem I am trying to solve, so I think a specific example would be helpful. Let's say there are XML descriptions of...
1
by: komaladevi | last post by:
can any one help me in writing acode -"how to edit "edit item template" dynamically""
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.