473,830 Members | 2,019 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

setattr getattr confusion

Hi,
Here's some code, it's broken:
class Key( object ):
def __init__(self):
self.props = KeyProps()
def __getattr__(sel f, v):
return getattr( self.props,v )
def __setattr__(sel f,var,val):
object.__setatt r__(self.props, var,val)

class KeyProps(object ):
def __init__(self):
self.x="NOT SET YET"
k1=Key()

It does not run because of the recursion that happens, but I don't know how
to lay this out.

I am trying to set the x value within props within Key:
k1.x="DAMN"
print k1.x

It seems to work, but it's really making a new 'x' in k1.
print k1.props.x
Shows "NOT SET YET", thus proving it failed to set x here.

I want to change k1.props.x by k1.x="something new" -- can this be done?

\d

Dec 8 '07 #1
6 4297
So you might want to describe your use-case.
Um.. I wanted an object with Key to hold other data. I wanted a way to set
that *other* data within Key without having to specify the "object
in-between" everytime.

k1.x = "ni!"

should perform:
k1.props.x = "ni!"

and
print k1.x
should perform:
print k1.props.x
I'll go look at your link. Thanks.

\d
Dec 8 '07 #2
On Dec 8, 6:06 am, Donn Ingle <donn.in...@gma il.comwrote:
Hi,
Here's some code, it's broken:

class Key( object ):
def __init__(self):
self.props = KeyProps()
def __getattr__(sel f, v):
return getattr( self.props,v )
def __setattr__(sel f,var,val):
object.__setatt r__(self.props, var,val)
If you define __setattr__ you can't initialize attributes the ordinary
way. Instead, use self.__dict__. (Once it's initialized, you can
refer to it in the ordinary way.) So do it like this:

class Key(object):
def __init__self):
self.__dict__['props'] = KeyProps()
def __getattr__(sel f,var):
return getattr(self.pr ops,var)
def __setattr__(sel f,var,val):
setattr(self.pr ops,var,val)
Carl Banks
Dec 8 '07 #3
On Sat, 08 Dec 2007 14:26:00 +0200, Donn Ingle wrote:
>So you might want to describe your use-case.
Um.. I wanted an object with Key to hold other data. I wanted a way to
set that *other* data within Key without having to specify the "object
in-between" everytime.
That's called "automatic delegation".
--
Steven
Dec 8 '07 #4
class Key(object):
def __init__self):
self.__dict__['props'] = KeyProps()
Okay - that's weird. Is there another way to spin this?
def __setattr__(sel f,var,val):
setattr(self.pr ops,var,val)
Perhaps by changing this one?

\d

Dec 8 '07 #5
Donn Ingle a écrit :
>>class Key(object):
def __init__self):
self.__dict __['props'] = KeyProps()

Okay - that's weird.
No, that's coherent. The default behavior (I mean, when there's no
descriptor involved etc) of __setattr__ is to store attributes in
instance.__dict __. So as long a you override __setattr__, you have to
take care of this by yourself.
Is there another way to spin this?
>>def __setattr__(sel f,var,val):
setattr(self. props,var,val)

Perhaps by changing this one?
If you know by advance which names should live in your object and/or
which should belong to the KeyProps instance, then you can check and
dispatch, ie:
class Key(object):
# names that must not be delegated to instance.props
_mynames = ['props', 'foo', 'bar']

def __setattr__(sel f, name, value):
if name in self._mynames:
object.__setatt r__(self, name, value)
else:
setattr(self.pr ops, name, value)

Dec 8 '07 #6
Thanks Bruno, I had to keep coding, so I used the long form
[Object.subobjec t.property = blah] anyway. It's long-winded, but
unambiguous.

\d

Dec 8 '07 #7

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

Similar topics

4
2018
by: Gerson Kurz | last post by:
I stumbled across this (while using my homebrewn enum class): class test: pass instance = test() setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123) I would've expected some kind of error message here when calling setattr(); after all, its not a regular attribute? Plus, documentation
4
1471
by: Alex | last post by:
I apologize for asking maybe a very trivial question. I have a new class object A with slots. One of the slots is, for example, object spam. Object spam, in turn, also has slots and one of them is attribute eggs. I need to assign a new value to eggs. In other words, I need to perform the following: A.spam.eggs=newValue The problem is that I have only a string s='spam.eggs' with which to work, so I cannot write an expression written...
8
1906
by: Steven D'Aprano | last post by:
I came across this unexpected behaviour of getattr for new style classes. Example: >>> class Parrot(object): .... thing = .... >>> getattr(Parrot, "thing") is Parrot.thing True >>> getattr(Parrot, "__dict__") is Parrot.__dict__ False
4
3689
by: Emin | last post by:
Dear experts, I got some unexpected behavior in getattr and copy.deepcopy (see transcript below). I'm not sure if this is actually a bug in copy.deepcopy or if I'm doing something too magical with getattr. Comments would be appreciated. Thanks, -Emin
10
2016
by: Paulo da Silva | last post by:
Hi! In a class C, I may do setattr(C,'x',10). Is it possible to use getattr/setattr for variables not inside classes or something equivalent? I mean with the same result as exec("x=10"). Thanks.
0
1204
by: Nathan Harmston | last post by:
Hi, I m trying to implement an object which contains lazy" variables. My idea is to alter the getattr and the setattr methods. However I keep on getting a recursion error. My idea is that the lazy variable can be stored in a variety of places, Database, PyTables etc. The lazy variable is a large variable and so I dont want to hold it in memory all of the time, I d rather just get it when needed and then store it for future work. Most...
0
1387
by: John Nagle | last post by:
Just noticed, again, that getattr/setattr are ASCII-only, and don't support Unicode. SGMLlib blows up because of this when faced with a Unicode end tag: File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag method = getattr(self, 'end_' + tag) UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 46: ordinal not in range(128)
4
1402
by: Rotlaus | last post by:
2 weeks ago i asked for a etended getattr() which worked really fine, but now i would love to have a extended setattr() as well. Lets assume i have some classes: class A(object): def __init__(self): self.B = B() class B(object):
4
10489
by: maestro | last post by:
Why are these functions there? Is it somehow more idiomatic to use than to do obj.field ? Is there something you can with them that you can't by obj.field reference?
0
10491
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 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...
1
10526
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10206
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9315
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6951
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();...
0
5617
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...
0
5780
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4411
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
2
3959
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.