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

instance vs class attributes

I come from a C++ background and am learning some of the details of
Python's OO capability and now have some questions. Given:

#!/bin/env python

class A(object):
_x = 10
def __init__(self): self.x = 20
def square(self): return self.x * self.x

print 'A.x = %d' % A._x
a = A()
print 'a.x = %d' % a.x
print 'a.square() = %d' %a.square()

I get the output:

A.x = 10
a.x = 20
a.square() = 400

Here are my questions:

1) What are the benefits of using a member variable without the 'self'
qualifier? (I think this is because you can use _x without an
instance of A().)

2) Is there a preferred coding style (_x vs self.x)?

3) Should private data be written as self._x instead of self.x?

Thanks.

Sarir
Jul 18 '05 #1
6 1634
Sarir said:
Here are my questions:

1) What are the benefits of using a member variable without the 'self'
qualifier? (I think this is because you can use _x without an
instance of A().)
No such thing as a benefit here. self.a inside a method is the same as a
outside (see code below for what I mean).
2) Is there a preferred coding style (_x vs self.x)?
This is essentially a non sequitur.
3) Should private data be written as self._x instead of self.x?


This is a long standing debate. The usual answer is "we are all grownups
here", meaning that self.x is preferred. However, I personally like self._x
to let potential users of my code know that I intended it to be private.

The code I was talking about:
class bob: .... a = 2
.... def get_a(self):
.... return self.a
.... def set_a(self,an_a):
.... self.a = an_a
.... abob = bob()
abob.get_a() 2 abob.a 2 abob.set_a(14)
abob.a 14 abob.get_a() 14 class carol:

.... self.a = 22
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in carol
NameError: name 'self' is not defined
James

--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 18 '05 #2
On Tuesday 29 March 2005 05:37 pm, James Stroud wrote:
1) What are the benefits of using a member variable without the 'self'
* *qualifier? (I think this is because you can use _x without an
* *instance of A().)


No such thing as a benefit here. self.a inside a method is the same as a
outside (see code below for what I mean).


By the way, here is some unintuitive behavior to think about:
class bob: ... a = 2
... def get_a(self):
... return self.a
... def set_a(self,an_a):
... self.a = an_a
... bob1 = bob()
bob1.a 2 bob1.set_a(4)
bob1.a 4 bob.a = 14
bob1.a 4 bob2 = bob()
bob2.a 14 bob.a = 99
bob2.a 99 bob1.a

4

James

--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 18 '05 #3
James Stroud said unto the world upon 2005-03-29 20:37:
Sarir said:
Here are my questions:
<SNIP>
3) Should private data be written as self._x instead of self.x?

This is a long standing debate. The usual answer is "we are all grownups
here", meaning that self.x is preferred. However, I personally like self._x
to let potential users of my code know that I intended it to be private.


<SNIP>
James


My understanding is that there is no such thing as true privacy with
Python, since you can always access self._name and self.__mangled_name
if you want to. (Though the later way of naming makes it a bit
difficult so as to strongly indicate it is discouraged Example below.)
Instead of private names, think of them as shy :-)

But I don't think it is correct to say the self.x form is preferred.
Some support tools, notably pydoc, understand convention that single
and double leading underscores means the name is shy and respect it:
class Shy: '''My silly example'''
def _shy_method(self):
'''I'm a shy docstring'''
pass
def public_method(self):
'''I'm a public docstring'''
pass
def __mangled_method(self):
'''I'm quite shy and a bit of a challenge to call'''
print "I've been mangled!"
help(Shy) Help on class Shy in module __main__:

class Shy
| My silly example
|
| Methods defined here:
|
| public_method(self)
| I'm a public docstring
You can still use pydoc on the shy methods, though:
help(Shy._shy_method) Help on method _shy_method in module __main__:

_shy_method(self) unbound __main__.Shy method
I'm a shy docstring
# calling a mangled method name from outside the class
shy = Shy()
shy.__mangled_method()
Traceback (most recent call last):
File "<pyshell#25>", line 1, in -toplevel-
shy.__mangled_method()
AttributeError: Shy instance has no attribute '__mangled_method' shy._Shy__mangled_method() Ive been mangled!


Best,

Brian vdB

Jul 18 '05 #4
>>> shy._Shy__mangled_method()
Ive been mangled!
Hi Brian,

can you explain how this could possibly work? First of all it's not
standard python usage,
and secondly it's not working on my computer...

pan

Jul 18 '05 #5
You need 2 underscores to mangle.

On Tuesday 29 March 2005 09:58 pm, runsun pan wrote:
shy._Shy__mangled_method()


Ive been mangled!
Hi Brian,

can you explain how this could possibly work? First of all it's not
standard python usage,
and secondly it's not working on my computer...

pan


--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 18 '05 #6
On Tue, 29 Mar 2005 17:34:50 -0700, Sarir Khamsi
<sa**********@raytheon.com> declaimed the following in comp.lang.python:
1) What are the benefits of using a member variable without the 'self'
qualifier? (I think this is because you can use _x without an
instance of A().)

class A(object):
_x = 10
def __init__(self):
self._x = 20
def square(self):
return (self._x * self._x, A._x * A._x)
def newval(self, vl):
A._x = vl #note no self...
a = A()
b = A()

print a.square()
print b.square()
b.newval(30)
print a.square()
print b.square()
-=-=-=-=-=-=-=-
(400, 100)
(400, 100)
(400, 900)
(400, 900)

The one without the self. prefix is shared by all instances of
A() objects. Note how changing A._x from within b.newval() also changed
the value computed by a.square(), not just that of b.square().

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #7

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

Similar topics

3
by: David MacQuigg | last post by:
I am writing a chapter for teaching OOP in Python. This chapter is intended as a brief introduction to replace the more complete discussion in Learning Python, 2nd ed, pp. 295-390. I need to...
5
by: Zhao Huang | last post by:
Hi, I'm new to python and I've come across a problem with my objects corrupting each other. class aclass: num = 0 l = ,] a = aclass()
8
by: Matthew Bell | last post by:
Hi, I've got a question about whether there are any issues with directly calling attributes and/or methods of a threaded class instance. I wonder if someone could give me some advice on this. ...
10
by: John M. Gabriele | last post by:
The following short program fails: ----------------------- code ------------------------ #!/usr/bin/python class Parent( object ): def __init__( self ): self.x = 9 print "Inside...
3
by: wolfgang.lipp | last post by:
some time after posting my `Linkdict recipe`__ to aspn__ -- basically, a dictionary with run-time delegational lookup, but this is not important here -- i thought gee that would be fun to make...
7
by: Simon Bunker | last post by:
Hi I have code similar to this: class Input(object): def __init__(self, val): self.value = val def __get__(self, obj, objtype): return self.value
7
by: JonathanB | last post by:
Ok, I know there has to be a way to do this, but my google-fu fails me (once more). I have a class with instance variables (or should they be called attributes, I'm newish to programming and get...
10
by: Steven W. Orr | last post by:
In the program below, I want this instance to end up calling repmeth whenever inst.m1 is called. As it is now, I get this error: Hello from init inst = <__main__.CC instance at 0x402105ec>...
0
by: Terry Reedy | last post by:
Fredrik Lundh wrote: If you do not want the instance created at all, you would have to write a custom .__new__ method, but that is tricky, something I would have to look up how to do, and most...
1
by: TomGo | last post by:
Hi All I want to read out the properties of a field by the instance, which is referenced by the corresponding field. I want to read out the attributes. In a class I wrote the following: ...
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: 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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
0
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...

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.