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

attributes of Python classes

I have started using classes with Python and have a question
about their use.

In Python, 'attributes are all "public" and "virtual" in C++
terms; they're all accessible everywhere and all looked up
dynamically at runtime' (Quoting "Learning Python", 2nd. ed.,
p367). It seems to me that two good conventions are to

(1) initialize all attributes in the __init__ function
(2) avoid creating new attributes elsewhere that are not initialized in
__init__

I have not followed these conventions so far, and sometimes
it is difficult for me to tell what attributes an instance of
a class has. Are these conventions good?
Jul 18 '05 #1
6 1771
be*******@aol.com wrote:
I have started using classes with Python and have a question
about their use.

In Python, 'attributes are all "public" and "virtual" in C++
terms; they're all accessible everywhere and all looked up
dynamically at runtime' (Quoting "Learning Python", 2nd. ed.,
p367). It seems to me that two good conventions are to

(1) initialize all attributes in the __init__ function
(2) avoid creating new attributes elsewhere that are not initialized
in
__init__

I have not followed these conventions so far, and sometimes
it is difficult for me to tell what attributes an instance of
a class has. Are these conventions good?


Yes, I think so, provided a key feature of the class in question isn't
that it's inherently dynamic (in which case it's inherently infeasible
to do this) -- an example might be a class that you'd like to mimic the
interface of a module, so it effectively acts like a dictionary but it
allows attribute access to access the dictionary as well.

I certainly follow them as best as is possible in my own code; I can
only think of once instance in an old project where I don't do that, and
it's marked as ugly in the code.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Everyone wants to look good at his own funeral.
-- Louis Wu
Jul 18 '05 #2
In article <40***************@alcyone.com>,
Erik Max Francis <ma*@alcyone.com> wrote:
be*******@aol.com wrote:
I have started using classes with Python and have a question
about their use.

In Python, 'attributes are all "public" and "virtual" in C++
terms; they're all accessible everywhere and all looked up
dynamically at runtime' (Quoting "Learning Python", 2nd. ed.,
p367). It seems to me that two good conventions are to

(1) initialize all attributes in the __init__ function
(2) avoid creating new attributes elsewhere that are not initialized
in
__init__

I have not followed these conventions so far, and sometimes
it is difficult for me to tell what attributes an instance of
a class has. Are these conventions good?


Yes, I think so, provided a key feature of the class in question isn't
that it's inherently dynamic (in which case it's inherently infeasible
to do this) -- an example might be a class that you'd like to mimic the
interface of a module, so it effectively acts like a dictionary but it
allows attribute access to access the dictionary as well.

I certainly follow them as best as is possible in my own code; I can
only think of once instance in an old project where I don't do that, and
it's marked as ugly in the code.


I agree that initializing all attributes in __init__ is a good idea.
Even if you initialize them to None and overwrite them in some other
method before ever accessing the value, it's still a nice way to help
soem future reader understand your class better. If it's a good idea to
have self-documenting code, I guess it's an even better idea to have
executable comments :-)
Jul 18 '05 #3
be*******@aol.com wrote:
I have started using classes with Python and have a question
about their use.

In Python, 'attributes are all "public" and "virtual" in C++
terms; they're all accessible everywhere and all looked up
dynamically at runtime' (Quoting "Learning Python", 2nd. ed.,
p367). It seems to me that two good conventions are to

(1) initialize all attributes in the __init__ function
(2) avoid creating new attributes elsewhere that are not initialized in
__init__

I have not followed these conventions so far, and sometimes
it is difficult for me to tell what attributes an instance of
a class has. Are these conventions good?


I actually go a very different way. Use properties/descriptors for
everything, with the properties declared directly in the class
definition something like so:

class SessionImporter( sessiondata.SessionData ):
"""Holder for importing data with an interactive session

Primary purpose of this class is to provide a way to safely
store partially-constructed records which may reference either
database-resident records, or other partially-constructed
records.
"""
sourceText = common.StringProperty(
"sourceText", """Source of the data being imported""",
defaultValue = "",
)
newObjectID = common.IntegerProperty(
"newObjectID", """Sequence for the newObjectID of newly created
objects""",
defaultValue = 0,
)
newObjects = common.DictionaryProperty(
"newObjects", """New objects, indexed by newObjectID""",
)
rootObjects = common.ListProperty(
"rootObjects", """IDs for each root-object to be stored""",
)

and then use generic __init__ and the like that can take any set of
specified properties. This way each attribute is fully documented, can
have intelligently calculated defaults, can be initialised anywhere,
etceteras, but there's not the huge collections of boilerplate
initialisation, copying, etceteras code that's needed with bare
attributes. The fact that it also allows for type-checking and
coercian, and generic code for working with properties, is a nice
side-effect :)

There's still the possibility of having properties without values, but
if that's undesired, just declare each with the default of None or "" or
whatever you like *for that particular property*.

Have fun,
Mike

_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/

Jul 18 '05 #4
Roy Smith a écrit :
In article <40***************@alcyone.com>,
Erik Max Francis <ma*@alcyone.com> wrote:

be*******@aol.com wrote:

I have started using classes with Python and have a question
about their use.

In Python, 'attributes are all "public" and "virtual" in C++
terms; they're all accessible everywhere and all looked up
dynamically at runtime' (Quoting "Learning Python", 2nd. ed.,
p367). It seems to me that two good conventions are to

(1) initialize all attributes in the __init__ function
(2) avoid creating new attributes elsewhere that are not initialized
in
__init__

I have not followed these conventions so far, and sometimes
it is difficult for me to tell what attributes an instance of
a class has. Are these conventions good?


Yes, I think so, provided a key feature of the class in question isn't
that it's inherently dynamic (in which case it's inherently infeasible
to do this) -- an example might be a class that you'd like to mimic the
interface of a module, so it effectively acts like a dictionary but it
allows attribute access to access the dictionary as well.

I certainly follow them as best as is possible in my own code; I can
only think of once instance in an old project where I don't do that, and
it's marked as ugly in the code.

I agree that initializing all attributes in __init__ is a good idea.
Even if you initialize them to None and overwrite them in some other
method before ever accessing the value, it's still a nice way to help
soem future reader understand your class better. If it's a good idea to
have self-documenting code, I guess it's an even better idea to have
executable comments :-)


I agree BUT there is 2 cases were I don't follow this rules :

1) I have a project that creates a lot of objects by reading a file. The
time is twice as needed if I initialize first the attribute and then set
them from the values given by the file...

2) When using an algorithm that need to decorate the object, it's easier
to just add attribute to the object rather than create a dictionnary or
something like that.

But for te sake of documentation, your rules sound good to me. For the
first problem, I don't know how to solve it nicely.

The second is not a problem because, the algorithm know what he's doing.

Yermat

Jul 18 '05 #5
I agree that initializing all attributes in __init__ is a good idea.
Even if you initialize them to None and overwrite them in some other
method before ever accessing the value, it's still a nice way to help
soem future reader understand your class better. If it's a good idea to have self-documenting code, I guess it's an even better idea to have
executable comments :-)


An alternative is to give attributes a default value of None as class
attributes. This avoid time and space overhead of doing same on per
instance basis. Instances only need instance-specific value when there is
one.

class C:
a = None # what a is
b = None # what b is

Terry J. Reedy


Jul 18 '05 #6
Terry Reedy a écrit :
I agree that initializing all attributes in __init__ is a good idea.
Even if you initialize them to None and overwrite them in some other
method before ever accessing the value, it's still a nice way to help
soem future reader understand your class better. If it's a good idea
to
have self-documenting code, I guess it's an even better idea to have
executable comments :-)

An alternative is to give attributes a default value of None as class
attributes. This avoid time and space overhead of doing same on per
instance basis. Instances only need instance-specific value when there is
one.

class C:
a = None # what a is
b = None # what b is

Terry J. Reedy


Ya right but then the documentation will not be very clear. I was
thinking of two version of my class. Let say A that does not initialize
its variable because it will be done later by the file reader. And B
that inherit A and initialize instance variables.

In the documentation it will be easier to understand which one to use.

Just ideas...
Yermat

Jul 18 '05 #7

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

Similar topics

145
by: David MacQuigg | last post by:
Playing with Prothon today, I am fascinated by the idea of eliminating classes in Python. I'm trying to figure out what fundamental benefit there is to having classes. Is all this complexity...
0
by: Iain | last post by:
In researching something else, I came across a comment about problems with problems with attributes in classes derived from ICollection. I seem to have hit this problem a while ago (I've been on...
4
by: acatejr | last post by:
I have a text file that I am parsing. Each line is of the form: max_time 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10 0.11 0.12 The first item is the field name and the next twelve items...
2
by: Jeff Rush | last post by:
While I have a reasonable understanding of the differences in new-style versus old-style classes, tonight while working a C extension module I realized I don't know how to indicate which style my C...
19
by: adriancico | last post by:
Hi I am working on a python app, an outliner(a window with a TreeCtrl on the left to select a document, and a RichTextBox at the right to edit the current doc). I am familiarized with OOP...
14
by: Tom Gur | last post by:
Hi, I'm new to python, and I can't seem to find in the docs how to create the python equivalent of what's called in most OOP languages "static classes", can you give me a hint ?
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: 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...
0
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,...
0
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...

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.