473,624 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1777
be*******@aol.c om 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.co m> wrote:
be*******@aol.c om 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.c om 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.Ses sionData ):
"""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.StringPr operty(
"sourceText ", """Source of the data being imported""",
defaultValue = "",
)
newObjectID = common.IntegerP roperty(
"newObjectI D", """Sequence for the newObjectID of newly created
objects""",
defaultValue = 0,
)
newObjects = common.Dictiona ryProperty(
"newObjects ", """New objects, indexed by newObjectID""",
)
rootObjects = common.ListProp erty(
"rootObject s", """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.co m> 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
dynamicall y 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
6286
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 unecessary? Here is an example of a Python class with all three types of methods (instance, static, and class methods). # Example from Ch.23, p.381-2 of Learning Python, 2nd ed. class Multi:
0
1068
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 something else). So if I derive a class from List<Dictionary>, for example and attempt to have a member with an XmlAttributeAttribute, it fails to serialize / deserialize the attribute. Is there any way round this?
4
1539
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 are values for each month in the year. There are multiple lines each for some different variable. I am able to parse this data easily enough, but what I'd like to do is have a class that stores all this infomormation using dynamic member...
2
1774
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 extension module should appear as. I'm following the Python docs for extended modules, but it doesn't say in there anyplace I can find which style I'm creating. My clue that something was wrong is when this: from cextension import Context
19
1740
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 concepts and terms but I lack practical experience
14
2275
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
8681
Oralloy
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8341
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
7170
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
6112
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
5570
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
4084
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
4183
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2611
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
1793
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.