SEARCH YOUR SOLUTION HERE  

overriding setting

,
this is my first post to the list :-) I've looked around a bit before
asking, and since I haven't found... I'm here to ask my question.

I'm trying to ovveride attribute setting, but I haven't still found
the right way to use all the fancy __get__, __set__ and
__getattribute__ :-)

I would like to retain initialization of an object by use of the = and
not as a function call. A simple example is this:

I want to define an "enhanced" list class, whose items will be other
(built in) lists and providing a "padding" method which fills all the
contained lists to the same lenght.
An example could be:

class myList(list):
def __init__(self):
self._max = None
list.__init__(self)
def pad(self):
for item in self:
if type(item)== list:
while len(item) < self._max:
item.append("")

Now the question is this:
I would like to initialize such an object in this way:
a = myList()
a = [[1, 2, 3], [4, 5, 6, 7]]
a.pad()
# and now a _should_ contain [[1, 2, 3, ""], [4, 5, 6, 7]]


Obviously this doesn't work, because when at the second line I do the
initialization, type(a) becomes , and so I get the
expected AttributeError since pad cannot be found.

A possible solution could be to create a container class, intercepting
every attribute accession with __getattribute__.
In this case I should refer to Container.myFirstList,
Container.mySecondList, which is ugly because of the need to refer to
Container first...(not to mention that I'm still working on making the
__getattribute__ work properly... :-) )


Do you have any suggestions or maybe I should simply stop trying to
do that and resort to adding some sort of insert or append method
(this is what I have done for the time being, but I found this
solution less appealing and nice ...)

thanks in advance,
Francesco
--
"Voil! In view, a humble vaudevillian veteran, cast vicariously as
both victim and villain by the vicissitudes of fate. This visage, no
mere veneer of vanity, is a vestige of the vox populi, now vacant,
vanished. However, this valorous visitation of a bygone vexation
stands vivified, and has vowed to vanquish these venal and virulent
vermin vanguarding vice and vouchsafing the violently vicious and
voracious violation of volition. The only verdict is vengeance; a
vendetta held as a votive, not in vain, for the value and veracity of
such shall one day vindicate the vigilant and the virtuous. Verily,
this vichyssoise of verbiage veers most verbose vis--vis an
introduction, so let me simply add that it's my very good honor to
meet you and you may call me V." -- V's introduction to Evey

Posted On: Monday 5th of November 2012 03:52:16 AM Total Views:  246
View Complete with Replies




Related Messages:

Problem in setting the include path   (65 Views)
Hi I am new to VC++.net, even I didn't have any exposure about C++ I have opened an existing project. But I am getting the errors in include directive #include when I compile the program the complier was unable to find the header file. Then I have created a folder called Test and include the file testnamespaces.h But still I am getting the same error. Can anyone please tell me How to set the include path.
help with setting path for scripting..   (66 Views)
i need help with python i recently ran a script that messed with my cdroms now there not detected to windows xp and i was wondering how to set the path for enabling scripting.. the script that messed with my cd roms is a=2 b=3 a=2*a b=3*b c=a+b print c please help
properties setting each other   (65 Views)
, I try to set two properties, "value" and "square" in the following code, and arrange it in such way that setting one property also sets another one and vice versa. But the code seems to get Python into infinite loop: >>> import math >>> class Squared2(object): def __init__(self, val): self._internalval=val self.square=pow(self._internalval,2) def fgetvalue(self): return self._internalval def fsetvalue(self, val): self._internalval=val self.square=pow(self._internalval,2) value = property(fgetvalue, fsetvalue) def fgetsquare(self): return self.square def fsetsquare(self,s): self.square = s self.value = math.sqrt(self.square) square = property(fgetsquare, fsetsquare) >>> a=Squared2(5) Traceback (most recent call last): File "", line 1, in a=Squared2(5) File "", line 5, in __init__ self.square=pow(self._internalval,2) File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare .... Is there a way to achieve this goal of two mutually setting properties
Blanket font setting?   (57 Views)
I'm doing an app with the AUI manager capabilities (using some of the wxPython demo's for help). is well, except I'm a bit disappointed with the font management. The default font for all the widgets (TextCtrl's, StaticText's etc) are a bit large for my design intent and as I try to adjust that, it appears I have to do a font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(9) Then, for every texty thing: myTextThing.setfont(font) someOtherThing.setfont(font) Thus if I have hundreds of texty things, I've got to assign that hundreds of times. Is there any sort of blanket font setting, perhaps like: wx.SystemSettings_SetFont(font) #this doesn't exist that could set everything with one fell swoop
Re: properties setting each other   (69 Views)
Thanks to for answers.. > *but*, if you want to add more logic in the setters, you could want to add two > extra methods : > > def _setsquare(self, v) : > # some extra logic here > self._square = s > > def fsetsquare(self,s): > self._setsquare(s) > self._setvalue = math.sqrt(s) > > def _setvalue(self, val): > # some extra logic here > self._internalval=val > > def fsetvalue(self, val): > self._setvalue(val) > self._setsquare=pow(val,2) > Thanks for that, I'll keep that in mind. > Note that if one property can really be computed from another, this kind of > thing could be considered as bad design (except if the computation is heavy). Hmm, why Is the line of thinking smth like: because the variables should be kept to minimum and they should be calculated at the moment they are neede
Best way to update a settings file?   (64 Views)
I'm thinking about writing a small script that will update an xml file with whatever game settings the user enters. I imagine that the user will have a single-screen GUI application with several different settings, like this: CROSSHAIRS ON LOCATION ON HEALTHBAR OFF etc..... These settings will somehow be toggleable with an ON/OFF button, or something. Anyway, I can think of two ways to do this: 1. After the user chooses his settings and clicks the Save button, Python reads all the settings from the GUI application and updates *every* entry in the xml file (whether it has changed or not). 2. After the user chooses his settings and clicks the Save button, Python reads all the settings from the GUI application, compares these settings to those in the xml file, and updates only the ones that have been changed. Now, #2 seems, at first glance, like the more efficient option, because you are only updating what needs to be updated, and leaving the rest alone. However, I wonder if the extra step of comparing all the settings from the user input and the xml file will end up taking longer than just simply rewriting all the settings. Probably neither method will take much longer than the other, but I'm asking more from a good design/efficiency standpoint. Which of these two methods is the better way, or is there perhaps another way I'm not thinking of
Re: Sending key-presses to other programs on Windows,and settings of controls?   (69 Views)
On Thu, Feb 21, 2008 at 1:20 PM, Tim van der Leeuw wrote: > I'm looking for ways to send keypresses to another application on Windows > XP, and to set values of Windows Controls (all of them text-boxes). Try . -- Cheers, Simon B. simon@brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
unified command line args, environment variables, .conf filesettings.   (77 Views)
On May 3, 12:16 pm, smitty1e wrote: > Just a fun exercise to unify some of the major input methods for a > script into a single dictionary. > Here is the output, given a gr.conf file in the same directory with > the contents stated below: > How about extending this to include other sources of control inputs. I think a reasonable heirarchy is: Interactive Input > Command Line Argument > Command Line Input File > Environment Variables > Local Defaults File > System Wide Defaults File > Installation Defaults File > 'Factory' Defaults File > In-Code Initialization Defaults
Re: Tkinter fonts setting   (69 Views)
On Tuesday 05 February 2008 15:22, Unnamed One wrote: > First question - is it possible to set > font to default OS font for window text > It would be preferable, while on my > Windows XP system Tkinter sets small > Helvetica-style font by default. > > Secondly, can I set font globally (or > specify "default" font for widgets) In > fact, all I want is to get default OS font > unless (rarely) I need to specify another. > >
overriding = operator   (64 Views)
I am developing something like a compiler in Python, a library that would help to generate machine-language code. One of the features is the following. When I want to generate a piece of code I want to declare variables as follows: x = var() y = var() This would generate no code, but it would mean that I need, say, two 32-bit integer variables. Then whenever I write something like x+y, the '+' operator is overriden in such a way that a code which computes the sum is generated. What I also want to do, I want to write something like z = var() z = x + y and I want a code which takes the sum of x and y and puts it in z to be generated. However in python z = x + y already has its meaning and it does something different from what I want. So I need something like 'overriding' =, which is impossible, but I look for a systematic approach to do something instead. It seems there are two ways to do what I need: 1. Implement a method 'assign' which generates the corresponding code to store value: z.assign(x + y) 2. Do the same as 1., but via property set methods. For example, this would look cleaner: z.value = x + y Which of these is preferrable Does anyone know any alternative ways Anton
trap setting attribute when the attribute is dict   (76 Views)
all, I have a question which might be simple or need some work around. I want to do something like this. My class/instance has a dict as a property. I want the instance to catch the change in the dict (change in some values, addition/deletion of key/value etc) to be recognized by the class instance. How can I do this Any suggestions are very well appreciated. Here is an example of what I want my class to behave: class test(object): def __init__(self): self._d = {} self._changed = False def getd(self): print 'called getd' return self._d # dont know what to do next def setd(self,val): print 'called setd', key, val self._d[key] = val self._changed = True d = property(getd,setd,None,None) def getc(self): return self._changed changed = property(getc,None,None,None) if __name__ == '__main__': obj = test() print 'obj.changed = ', obj.changed print # I want obj to know that its propety d being changed here print "t.d['a'] = 1" obj.d['a'] = 1 print # I want the "changed" property to be True print 'obj.changed = ', obj.changed -- yosuke kimura Center for Energy and Environmental Resources The Univ. of Texas at Austin, USA
automatically setting platform-dependent location for Distutils "install-scripts"?   (92 Views)
all, I am developing a Python-based tool that will be deployed both in a Windows and in a Linux environment, and I have a question concerning the use of the Distutils module to manage the installation of the tool in a transparent manner. A bit of background info: 1. (I am using Python version 2.5) 2. Let's assume that the tool is named "xyz" 3. It is internally partitioned into two parts: xyzScript.py -- the front-end script that the users actually invoke, and xyzPackage -- a package containing the "guts" of the tool 4. Users do not really care where the "xyzPackage" part is installed -- and thus by default it will be installed into Python's standard "site-packages" directory. 5. However, users *do* care where the "xyzScript.py" part is installed Now, I have created a Distutils-based "setup.py" script that looks like this: from distutils.core import setup > > setup(name='xyz', > version="1.0", > # provide other metadata, such as 'description', 'author', 'author_email', 'url', ... etc. > > packages=['xyzPackage'], > > scripts=['xyzScript.py']) > .... that takes care of the above concerns, and also accepts a "setup.cfg" configuration file that allows the user to control into which directory to install the "xyzScript.py" part, as follows: > > [install] > install-scripts=C:\xyzScriptDirectory > And thus, here is my problem: [1] At any given moment, the directory name specified in the above "setup.cfg" file can be either a "Windows-style" directory (as is shown above) or a "Linux-style" directory (say "/opt/xyzScriptDirectory"), but not both! [2] I would like to have a *single* "setup.cfg" file that can nevertheless be used for *both* Windows and Linux, *without* having to be edited by the user. For example, it would be really nice if I can have a customized "setup.cfg" file that looks like: > > [install] > install-scripts-Windows=C:\xyzScriptDirectory > install-scripts-Linux=/opt/xyzScriptDirectory > .... and then some part of Distutils can query "os.name" and set the "real" 'install-scripts' option to the appropriate one of these two choices. I assume this can be done by "overriding" and customizing part of Distutils. Indeed, I have already done something similar by overriding "distutils.command.build_scripts" to use a customized "copy_scripts()" method. However, it is not clear to me in what manner I can/should override "distutils.command.install_scripts" to achieve the effect that I dee. Is this at all the way to go, or might there be a totally obvious way to do this that I am currently overlooking If anyone has similar experience in tweaking Distutils, I would be most appreciative of any advice that you can offer.
Question on overriding implicit lookups   (69 Views)
David Ells a crit : > In Python we have a wonderful facility for customizing attribute > access by defining __getattr__ or __getattribute__ in our classes. > Unfortunately (or perhaps fortunately, for reasons I don't know), this > facility only works for explicit attribute access, i.e. accessing > foo.bar. What I am in need of, for reasons I'll keep out of the > discussion for now, is a similar facility for implicit attribute > access, such as the call to foo.__len__ when something like len(foo) > is executed. I would like some way to customize access during these > implicit lookups without having to define each one in the class > myself. Essentially what I am looking for is a mechanism like > __getattribute__, only one that will work for these implicit lookups > to functions like __len__, __str__, __getitem__, and so on. Hopefully > my question makes sense. An obvious solution would be to define "each one" of these magic methods in a mixin class. Else, here's a Q&D but working solution : class Test(object): def _get_magic_attribute(self, name): return "YADDA YADDA" for _name in ('__len__', '__str__', '__repr__'): exec "%s = lambda self, _name='%s' : " \ "self._get_magic_attribute(_name)" % (_name, _name) del _name For a cleaner version, you may want to use a custom metaclass, but that seems a bit overkill to me.
Help setting default class attributes   (73 Views)
Hi all, I have the following piece of code and I wanted to set the default attributes based on a dictionary. What I am looking for is a way to take PIPODEFAULTS and assign each one as an attribute for the class pipo. Can someone show me how to do this by iterating over the PIPODEFAULTS and assign them. What I would expect to be able to do is call the class and modify them. example: a = pipo() print a.caseSensitivity "preserve" a.caseSensitivity = "lower" print a.caseSensitivity "lower" Lastly - here is my code: class pipo: PIPODEFAULTS={ "caseSensitivity" : "preserve","cellMapTable" : "","checkPolygon" : "nil","compression" : "none", "convertDot" : "ignore","convertPathToPoly" : "nil","convertToGeo" : "nil","dumpPcellInfo" : "nil", "snapToGrid" : "nil","techFileChoice" : "nil","units": "micron","useParentXYforText" : "nil","viewName" : "layout", } def __init__(self, *args, **kwargs): """This simply will run a PIPO stream out """ # Setup Logging self.pipoargs=self.setdefaults() def setdefaults(self): for x in self.PIPODEFAULTS: self.log.debug("Setting %s to %s" % (x, self.PIPODEFAULTS[x]))
overriding base class   (53 Views)
I want to develop a following lib: lib space user space A -> B -> | -> user_class however A and B are abstrac enough to have following: user_super_base_class -> | -> A -> B -> | -> user_class user space lib space user spaca Any idea how to do that -- alfz1