Hi,
I try to define a (new-style) class who:
- have a __slots__ defined to be strict attributes,
- return None if the attribute is 'ok' but not set, or raise a 'normal'
error if the attribute isn't in __slots__.
This code runs, but is it the good way?
Thanks.
class test(object):
__slots__ = ['id']
def __getattr__(sel f, attr):
if not attr in self.__slots__: raise AttributeError
try:
return self.attr
except:
return None 1 2699 pa***********@f ree.fr wrote:
Python has both __getattribute_ _() and __getattr__(). While
__getattribute_ _() will always be called if you ask for an attribute
__getattr__() serves only as fallback if the attribute if not found by
other means. I try to define a (new-style) class who: - have a __slots__ defined to be strict attributes,
__slots__ is a performance/memory optimization. Using __slots__ to introduce
bondage & discipline through the backdoor is against Python's spirit.
- return None if the attribute is 'ok' but not set, or raise a 'normal' error if the attribute isn't in __slots__.
The approach you have chosen is a very ineffective one. Why don't you just
set the attribute to a default value in the initializer?
This code runs, but is it the good way?
I don't think so...
class test(object): __slots__ = ['id'] def __getattr__(sel f, attr): if not attr in self.__slots__: raise AttributeError try: return self.attr
The line above does not do what you think it does. It just calls
test_instance._ _getattr__("att r"), and since "attr" is not in __slots__ it
raises an AttributeError.
except: return None
You should get the same effect with class T(object):
.... __slots__ = ["id"]
.... def __getattr__(sel f, name):
.... if name not in self.__slots__:
.... raise AttributeError
.... return 42 # for better visibility
.... t = T() t.id
42 t.whatever
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in __getattr__
AttributeError t.id = "something else" t.id
'something else' t.whatever = "something else"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'T' object has no attribute 'whatever'
Peter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: flori |
last post by:
i try to greate somthing like this
class ca(object): __slots__ = ("a",)
class cb(ca): __slots__ = ("a","b")
class cc(ca): __slots__ = ("a","c")
class cd(cb,cc): __slots__ = ("a","b","c","d")
but i didn't find a simple solution
so i'm using a metaclass that generate a __slots__-free and a
__slots__-version
|
by: Ruud de Jong |
last post by:
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.
I thought I could just use __getattribute__ for this purpose.
This works fine if I already have an instantiation of the class,
but not when I try this on the class object directly.
A bare bones...
|
by: Nick Jacobson |
last post by:
The __slots__ attribute of new-style classes can reduce memory usage
when there are millions of instantiations of a class.
So would a __slots__ attribute for functions/methods have a similar
benefit? i.e. could a function using __slots__ use significantly less
memory, and therefore run faster, if called millions of times?
If so, it will...
|
by: Ewald R. de Wit |
last post by:
I'm running into a something unexpected for a new-style class
that has both a class attribute and __slots__ defined. If the
name of the class attribute also exists in __slots__, Python
throws an AttributeError. Is this by design (if so, why)?
class A( object ):
__slots__ = ( 'value', )
value = 1
def __init__( self, value = None ):
|
by: Barry Kelly |
last post by:
I'm running this version of Python:
Python 2.4.3 (#1, May 18 2006, 07:40:45)
on cygwin
I read in the documentation that these two expressions are
interchangeable:
x.__getattribute__('name') <==> x.name
| |
by: Pedro Werneck |
last post by:
Hi all
I noticed something strange here while explaining decorators to someone.
Not any real use code, but I think it's worth mentioning.
When I access a class attribute, on a class with a custom metaclass with
a __getattribute__ method, the method is used when acessing some
attribute directly with the class object, but not when you do...
|
by: Licheng Fang |
last post by:
Python is supposed to be readable, but after programming in Python for
a while I find my Python programs can be more obfuscated than their C/C
++ counterparts sometimes. Part of the reason is that with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of...
|
by: Adam Donahue |
last post by:
As an exercise I'm attempting to write a metaclass that causes an
exception to be thrown whenever a user tries to access
'attributes' (in the traditional sense) via a direct reference.
Consider:
class X( object ):
y = 'private value'
def get_y( self ): return self.y
|
by: bukzor |
last post by:
I want to make a MixIn class that waits to initialize its super-
classes until an attribute of the object is accessed. Not generally
useful, but desirable in my case. I've written this, and it works, but
would like to take any suggestions you guys have. I've commented out
the "delattr" call because it throws an AttributeError (although I...
|
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. ...
|
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...
| |
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...
|
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...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
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...
|
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...
|
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: 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...
| |