473,606 Members | 2,885 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Use of __slots__

Hi:

I am puzzled about the following piece of code which attempts to create
a class that can be used as record or struct with a limited set of
allowed attributes that can be set into an instance of the class.

class RecordClass(obj ect):
__slots__ = ["foo"]
def __init__(self, args):
print "Initial slots = ", RecordClass.__s lots__
RecordClass.__s lots__ = list(args)
print "Final slots = ", RecordClass.__s lots__
pass

def new_record(slot list):
return RecordClass(slo tlist)

if __name__ == "__main__":
record1 = new_record(["age", "name", "job"])
record1.age = 27
record1.name = 'Fred'
record1.job = 'Plumber'
record1.salary = 50000

When executed I get:

Initial slots = ['foo']
Final slots = ['age', 'name', 'job']
Traceback (most recent call last):
File "D:\Programming Projects\JustFo rTesting\record classes.py", line
37, in ?
record1.age = 27
AttributeError: 'RecordClass' object has no attribute 'age'

I don't understand why I cannot set an attribute 'age' into record1.

Thanks,

Don.

Feb 26 '06 #1
2 1209
On Sun, 26 Feb 2006 17:01:45 -0500, Don Taylor wrote:
Hi:

I am puzzled about the following piece of code which attempts to create
a class that can be used as record or struct with a limited set of
allowed attributes that can be set into an instance of the class.

class RecordClass(obj ect):
__slots__ = ["foo"]
You define a RecordClass with a single slot, "foo".

[snip]
I don't understand why I cannot set an attribute 'age' into record1.


Because you defined the class with only a slot for "foo", not "age".

Re-defining the __slots__ attribute at runtime does not add or subtract
slots from the class. It just breaks your class.

If you want to add and delete arbitrary attributes at runtime, don't use
slots.
--
Steven.

Feb 26 '06 #2
Steven is right, however, there is a way:

def new_record(slot list):
class R(object):
__slots__ = slotlist
return R()

record1 = new_record(["age", "name", "job"])
record1.age = 27
record1.name = 'Fred'
record1.job = 'Plumber'
record1.salary = 50000

Feb 26 '06 #3

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

Similar topics

1
1988
by: anabell | last post by:
I have a code like this: sqlString = 'INSERT INTO ' + self.TableName + ' VALUES (' + self.TableFields + ')' self.cursor.execute(sqlString, self.__dict__) This works correctly. However, I'm applying __slots__ in my script. And doing so would need the above statement modified. How will __slots__ perform the same task defined above? Is there a container that holds the values of attributes contained in __slots__? In __dict__, you have...
9
3076
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
5
2925
by: Jean Brouwers | last post by:
Classes using __slots__ seem to be quite a bit smaller and faster to instantiate than regular Python classes using __dict__. Below are the results for the __slots__ and __dict__ version of a specific class with 16 attributes. Each line in the tables shows the number of instances created so far, the total memory usage in Bytes, the CPU time in secs, the average size per instance in Bytes and the average CPU time per instance in...
3
1632
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 hopefully be in a future version of Python.
7
1658
by: Porky Pig Jr | last post by:
Hello, I"m still learning Python, but going through the Ch 5 OOP of Nutshell book. There is discussion on __slots__, and my understanding from reading this section is that if I have a class Rectangle (as defined in some prior sections), and then I provide definition class OptimizedRectangle(Rectangle): __slots__ = 'width', 'heigth' I can use the instance of OptimizedRectangle, say, x, with 'width' and 'heigth', but (quoting the book)...
2
4969
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 ):
3
1566
by: Schüle Daniel | last post by:
Hello, consider this code >>> class A(object): .... def __init__(self): .... self.a = 1 .... self.b = 2 .... >>> class B(A):
1
2706
by: pascal.parent | last post by:
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.
3
1614
by: John Machin | last post by:
I have stumbled across some class definitions which include all/most method names in a __slots__ "declaration". A cut-down and disguised example appears at the end of this posting. Never mind the __private_variables and the getter/setter approach, look at the list of methods in the __slots__. I note that all methods in an instance of a slotted class are read-only irrespective of whether their names are included in __slots__ or not:...
27
1725
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 declaring them explicitly as one will do with C structs. So, what used to be struct nameval { char *...
0
8443
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
8107
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
8315
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
6792
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...
1
5971
isladogs
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5467
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
3945
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...
1
2452
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
1
1565
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.