Python Class Best Practice

Gary Herron gherron at islandtraining.com
Tue Dec 4 18:51:18 EST 2007


Rod Person wrote:
> I've been doing python programming for about 2 years as a hobby and now
> I'm finally able to use it at work in an enterprise environment. Since
> I will be creating the base classes and libraries I wondering which why
> is consider best when creating python classes:
>
> 1:
> class Foo(object):
>   member1=''
>   member2=0
>  
>   def __init__(self,member1='',member2=0):
>     self.member1 = member1
>     self.member2 = member2
>
> 2:
> class Foo(object):
>     def  __init__(self,member1='',member2=0):
>         self.member1 = member1
>         self.member2 = member2
>
>
Both examples will store values for member1 and member2 in every
instance.  Any code that accesses self.member1 (or 2) will get the value
stored in the instance. 

Example 1 which also creates two *class* members of the same name won't
affect the conclusion of the previous paragraph.  The two values in the
class will be shadowed by each instances members of the same name.

But now I need to ask, what did you expect to happen here? 

 * If you thought those two extra assignments in example 1 effected the
execution or storage in the __init__ (or any other method), you were
mistaken.

 * If you really wanted class members (i.e., values shared by ALL
instances), then they really shouldn't have the same name as instance
members.  You would surely confuse them at some point.

 * If you *really* wanted two class members *AND* two instance members
with the same names, (WHY???) then example 1 will do so, but you'll have
to access the instance members as self.member1 and the class members as
Foo.member1. 

Gary Herron




More information about the Python-list mailing list