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__(sel f, 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__(sel f, 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 5 14572
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
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__(sel f, 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__(sel f, 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__.u pdate(dbvaluedi ct)
>>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
On Aug 17, 5:09 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.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__(sel f, 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__(sel f, 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__(sel f, 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__(sel f, 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,"pr opName", property(fget = ...,
fset = ...,
fdel = ...,
doc = ...) )
obj = super(AClass, cls).__new__(cl s)
return obj
- Rafe
En Tue, 19 Aug 2008 15:02:29 -0300, Rafe <ra*******@gmai l.comescribi:
On Aug 17, 5:09 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.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,"pr opName", property(fget = ...,
fset = ...,
fdel = ...,
doc = ...) )
obj = super(AClass, cls).__new__(cl s)
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 instaniate a new instance
e.g.
string userinput = "classB"
|
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 dynamically using a html-table....
i want to display dynamically on each row one button, and dont use
datagrid.
|
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.
|
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 be able to generate and compile the project on the enviroments where Visual Studio.Net is not installed.
Thanks and Regards,
Anubhav Jain
MTS
Persistent Systems Pvt. Ltd.
Ph:+91 712 2226900(Off) Extn: 2431
Mob : 094231 07471
|
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(){},
my_meth2: function(){}
});
to define new methods on the MyObj prototype object. Object.extend
| |
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 server side code.
How can make this text box accessable in another "sub" or "button2"
click event?
Any help is greatly appreciated.'
thanks
|
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 paper written on this
subject.
On the Expressive Power of Programming Languages, by Matthias
Felleisen, 1990.
http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
|
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 products like this one:
<!-- File: Products.xml -->
...
<Product id="p1">
|
by: komaladevi |
last post by:
can any one help me in writing acode -"how to edit "edit item template" dynamically""
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |