473,779 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cool object trick

I read some discussion on this list before about how sometimes it's
useful to create a generic object class that you can just stick
attributes to. I was reading the PyPanel source (not written by me) and
I came across this:

#----------------------------------------------------------------------------

class Obj(object):
#----------------------------------------------------------------------------

""" Multi-purpose class """
#----------------------------
def __init__(self, **kwargs):
#----------------------------
self.__dict__.u pdate(kwargs)

Normally I'd just use class Obj(object): pass, but the advantage to this
method is you can create an Obj like this:

Obj(id="desktop ", last=0, color=self.getC olor(DESKTOP_CO LOR))

You can pass all the attributes you want the object to have this way.
Nifty :)

Sorry if this has been posted before, but I haven't seen it.
Jul 18 '05 #1
3 1434
dataangel wrote:
Normally I'd just use class Obj(object): pass, but the advantage to this
method is you can create an Obj like this:

Obj(id="desktop ", last=0, color=self.getC olor(DESKTOP_CO LOR))

You can pass all the attributes you want the object to have this way.
Nifty :)


Yup, that's basically what I was proposing in the pre-PEP:

http://mail.python.org/pipermail/pyt...er/252621.html

I've let it slide for a bit here, but my intent is to make a patch that
puts something like the pre-PEP class into the collections module and
then send in the PEP. I've been kinda busy recently, and it's not quite
trivial since Bunch is in Python and currently the collections module is
in C, but hopefully in the next few weeks I'll have the time.

Steve
Jul 18 '05 #2
Kinda cool.

It's occured to me that just about everything Pythonic can be done with
dicts and functions. Your Obj is just a dict with an alternate syntax. You
don't have to put quotes around the keys. But that's cool.
class struct(object):
def __init__(self, **kwargs):
self.__dict__.u pdate(kwargs)

# Indented this way, it looks like a struct:
obj = struct( saying = "Nee"
, something = "different"
, spam = "eggs"
)

print obj.spam

# Is that really much different from this?

obj2 = { "saying" : "Nee"
, "something" : "different"
, "spam" : "eggs"
}

print obj2["spam"]
Jul 18 '05 #3
has
Jive wrote:
# Is that really much different from this?


Functionally, no. However it can help make code more readable when
dealing with complex data structures, e.g. compare:

obj.spam[1].eggs[3].ham

to:

obj["spam"][1]["eggs"][3]["ham"]

I've used it a couple times for this particular reason and it
definitely has its niche; though I'm not sure it's sufficiently common
or useful to justify its inclusion it in the standard library, and it's
trivial to whip up as-and-when it's needed.

BTW & FWIW, I think the usual name for this kind of structure is
'record' (or 'struct' in C).

HTH

has

Jul 18 '05 #4

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

Similar topics

5
2125
by: Jeff Greenberg | last post by:
Not an experienced c++ programmer here and I've gotten myself a bit stuck. I'm trying to implement a class lib and I've run into a sticky problem that I can't solve. I'd appreciate any help that I can get! Consider 3 classes in the following heirarchy: base / \ deriv1 deriv2 \
0
881
by: John Bailo | last post by:
I just read a great article on object serialization in .NET http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=236 Being able to tag member in an object as Xml elements is /very/ cool. I've implemented in a smart client to retain the selectedindex of comboboxes between sessions.
1
7849
by: Kristian Kjems | last post by:
Look at the Code Snippet below: It is not possible to Deserialize the Animal in animalStr directly because the type of the animal is not known. Deserializing into the abstract type will not work because the xml serilization in animalStr contains more than an Animal, it contains either Cat or Dog. Is there a neat way of dealing with deserilization of abstract types? ------------- Code Snippet ------------- abstract public class Animal {
7
7355
by: Carsten H. Pedersen | last post by:
Hello I want to create a kind of shared object. I have created a class, Counter, which you can then import. Through the Counter class, i would like to have access to a shared object. Lets say that Counter contains only an int, initialised to 1. Each time a class importing Counter would do Counter.getNextNumber(), the getNextNumber() method would increase the local int, and return the next number.
44
3387
by: petermichaux | last post by:
Hi, I have been using the following line of code to create an object called "Serious" if it doesn't already exist. if (Serious == null) {var Serious = {};} This works in the scripts I use it but but www.jslint.com is not happy with me.
2
3601
by: HeroinNO.4 | last post by:
Copy the code below and save in a .htm file, for example : 1.htm, then run it in browser, you'll see a cool count down timer ! If it doesn't work, you may open http://www.fillweb.com in IE and View->Source, and the latest version of count down timer will show you ! <html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
4
1808
by: =?Utf-8?B?UmljaA==?= | last post by:
Hello, In my vb2005 app I create 3 datatables in the Datasource area, tbl1, tbl2, tbl3. tbl1 contains 1 column, tbl2 contains 2 columns tbl3 contains 3 columns. Based on selections from a form, I want to populate on 1 of the 3 tables with data and use the selected table throughout some procedure - the table and the data that it contains will have to persist throughout the life of the application. So instead of having a bunch of...
0
1301
by: [Cool staff!||Hi! I think this need for || Help me | last post by:
http://con-cern.org/files/2007/5/xenical-21024312.html cheap xenical http://con-cern.org/files/2007/5/auto-21024411.html auto loan refinance http://tag-dev.jot.com/WikiHome/pharmacy/xenical_html___117970823717048_96302128227356?jot.viewName=xenical.html&theme=none buy xenical http://tag-dev.jot.com/WikiHome/pharmacy/auto_html___117970831070975_10304845439619?jot.viewName=auto.html&theme=none auto loan refinance ,...
2
1552
by: Hoss | last post by:
I created this cool game. It was made entirely with JavaScript (and a tiny bit of PHP) <a href="http://beem.awardspace.com">http://beem.awardspace.com</a> Snippet from the explanation <blockquote> HE OBJECT OF BEEM
0
9632
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9471
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10136
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...
0
9925
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
8958
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
7478
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
5372
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
5501
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2867
bsmnconsultancy
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.