473,383 Members | 1,877 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,383 software developers and data experts.

how do i create such a thing?

I want to create a class called DefaultAttr which returns a default
value for all attributes which haven't been given values yet. It will
work like this:
x = DefaultAttr(99)
print x.foo 99 print x.bar 99 x.foo = 7
print x.foo

7

I already have a similar class called DefaultDict which works similarly
which I assume would be a good thing to use.

Lowell
Jul 18 '05 #1
7 1366
Hi,

If you need direct access to some atribute, use object.__getattribute__.

class DefaultAttr(object): .... def __init__(self, default):
.... self.default = default
.... def __getattribute__(self, name):
.... try:
.... value = object.__getattribute__(self, name)
.... except AttributeError:
.... value = self.default
.... return value
.... x = DefaultAttr(99)

print x.a 99 x.a = 10
print x.a 10

On Sun, 30 Jan 2005 13:54:38 -0800
Lowell Kirsh <lk****@cs.ubc.ca> wrote:
I want to create a class called DefaultAttr which returns a default
value for all attributes which haven't been given values yet. It will
work like this:
>> x = DefaultAttr(99)
>> print x.foo 99 >> print x.bar 99 >> x.foo = 7
>> print x.foo

7

I already have a similar class called DefaultDict which works
similarly which I assume would be a good thing to use.

Lowell
--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #2
Pedro Werneck wrote:
If you need direct access to some atribute, use object.__getattribute__.
class DefaultAttr(object):
... def __init__(self, default):
... self.default = default
... def __getattribute__(self, name):
... try:
... value = object.__getattribute__(self, name)
... except AttributeError:
... value = self.default
... return value
...
x = DefaultAttr(99)
print x.a 99
x.a = 10
print x.a

10


Of if you only want to deal with the case where the attribute doesn't
exist, you can use getattr, which gets called when the attribute can't
be found anywhere else:

py> class DefaultAttr(object):
.... def __init__(self, default):
.... self.default = default
.... def __getattr__(self, name):
.... return self.default
....
py> x = DefaultAttr(99)
py> x.a
99
py> x.a = 10
py> x.a
10

Steve
Jul 18 '05 #3
Steven Bethard <st************@gmail.com> wrote:
Of if you only want to deal with the case where the attribute doesn't
exist, you can use getattr, which gets called when the attribute can't
be found anywhere else:

py> class DefaultAttr(object):
... def __init__(self, default):
... self.default = default
... def __getattr__(self, name):
... return self.default
...
py> x = DefaultAttr(99)
py> x.a
99
py> x.a = 10
py> x.a
10


This is a good approach, but it's fragile regarding specialnames.
class DefaultAttr(object): .... def __init__(self, default): self.default = default
.... def __getattr__(self, name): return self.default
.... import copy
copy.copy(DefaultAttr(99))

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/local/lib/python2.4/copy.py", line 87, in copy
rv = reductor(2)
TypeError: 'int' object is not callable

There are many more, worse example for classic classes, but even in
newstyle classes you must consider that once in a while a system routine
will try a getattr(someinst, '__aspecialname__', None) or the like --
and your class is making its instances claim to have ANY special name
that may be introspected for in this way. This can be a pernicious lie,
since your class in fact has no idea whatsoever what that specialname
and the corresponding value might be for.

It's HIGHLY advisable to have your __getattr__ methods raise
AttributeError for any requested name that starts and ends with double
underscores, possibly with some specific and specifically designed
exceptions.
Alex
Jul 18 '05 #4
What might these exceptions be?
It's HIGHLY advisable to have your __getattr__ methods raise
AttributeError for any requested name that starts and ends with double
underscores, possibly with some specific and specifically designed
exceptions.
Alex

Jul 18 '05 #5
Lowell Kirsh <lk****@cs.ubc.ca> wrote:
What might these exceptions be?
It's HIGHLY advisable to have your __getattr__ methods raise
AttributeError for any requested name that starts and ends with double
underscores, possibly with some specific and specifically designed
exceptions.


For example, delegation of such requests to some other object:
def __getattr__(self, name):
return getattr(self._delegate, name)

In such cases you may decide you do not need to block __specials__,
because you're OK with having self._delegate supply them or be
responsible to raise AttributeError if necessary.
Alex
Jul 18 '05 #6
I'm not sure I get it. What's the purpose of using a delegate rather
than having the object itself supply the return value?

Alex Martelli wrote:
Lowell Kirsh <lk****@cs.ubc.ca> wrote:

What might these exceptions be?

It's HIGHLY advisable to have your __getattr__ methods raise
AttributeError for any requested name that starts and ends with double
underscores, possibly with some specific and specifically designed
exceptions.

For example, delegation of such requests to some other object:
def __getattr__(self, name):
return getattr(self._delegate, name)

In such cases you may decide you do not need to block __specials__,
because you're OK with having self._delegate supply them or be
responsible to raise AttributeError if necessary.
Alex

Jul 18 '05 #7
Lowell Kirsh wrote:
I'm not sure I get it. What's the purpose of using a delegate rather
than having the object itself supply the return value?

Alex Martelli wrote:
Lowell Kirsh <lk****@cs.ubc.ca> wrote:

What might these exceptions be?
It's HIGHLY advisable to have your __getattr__ methods raise
AttributeError for any requested name that starts and ends with double
underscores, possibly with some specific and specifically designed
exceptions.


For example, delegation of such requests to some other object:
def __getattr__(self, name):
return getattr(self._delegate, name)

In such cases you may decide you do not need to block __specials__,
because you're OK with having self._delegate supply them or be
responsible to raise AttributeError if necessary.
Alex


The point is that you can keep a reference to some object, and it's the
next best thing to having subclassed the object's class but with closer
control.

regards
Steve

A: Top-posting
Q: What puts things in the wrong order on newsgroup postings
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.python.org/pycon/2005/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #8

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

Similar topics

9
by: Lauren Quantrell | last post by:
Is there a way to create a text file (such as a Windows Notepad file) by using a trigger on a table? What I want to do is to send a row of information to a table where the table: tblFileData has...
0
by: Alf P. Steinbach | last post by:
The seventh part of my attempted Correct C++ tutorial is now available, although for now only in Word format (use free Open Office if no Word), and also, it's not yet been reviewed at all -- ...
7
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I...
15
by: Amit D.Shinde | last post by:
I am adding a new picturebox control at runtime on the form How can i create click event handler for this control Amit Shinde
9
by: Surrealist | last post by:
I need something likes as when I create an event procedure. I can use top-left and top-right dropdown list of code editor to select object and its exposed events respectively. Then, the IDE,...
24
by: M O J O | last post by:
Hi, Instead of doing this.... Public Class Form1 Public Shared Sub CreateAndShow() Dim f As New Form1 f.Show() End Sub
23
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these...
4
by: JohnnyDeep | last post by:
I am trying to create a store proc that contain a create index with the cluster option and I receive DB21034E The command was processed as an SQL statement because it was not a valid Command...
15
by: lxyone | last post by:
Using a flat file containing table names, fields, values whats the best way of creating html pages? I want control over the html pages ie 1. layout 2. what data to show 3. what controls to...
2
by: semaj.remle 'at' gmail | last post by:
For files saved in source control, is it better to use code to DROP/ CREATE a procedure like this: ------------------------------------------------------------------ IF OBJECT_ID ('procName') IS...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
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: 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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.