Re: Python Class Best Practice

Discussion in 'Python' started by Gary Herron, Dec 4, 2007.

  1. Gary Herron

    Gary Herron Guest

    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
     
    Gary Herron, Dec 4, 2007
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?YmFseXN0eWs=?=
    Replies:
    1
    Views:
    5,722
    Karl Seguin
    Dec 31, 2005
  2. Rod Person

    Python Class Best Practice

    Rod Person, Dec 4, 2007, in forum: Python
    Replies:
    4
    Views:
    346
    MarkE
    Dec 12, 2007
  3. Neil Chambers
    Replies:
    2
    Views:
    498
    Neil Chambers
    Sep 4, 2008
  4. Intransition
    Replies:
    4
    Views:
    133
    David A. Black
    Aug 14, 2009
  5. oldyork90
    Replies:
    1
    Views:
    175
    Jeremy J Starcher
    Sep 10, 2008
Loading...

Share This Page