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

"Protected" property in Python?

I'm want to create a superclass with nothing but attributes and properties.
Some of the subclasses will do nothing but provide values for the
attributes.

(I'd also like to make sure (1) that the subclass provides actual values
for the attributes and (2) that no "client" module adds or removes
attributes or properties, but I don't know how to do those.)

I don't understand what I'm doing wrong, or maybe what I want to do is
impossible. Here's a stripped down version of the code:

----------------------------------------------------------------
#! /usr/bin/python
class SuperClass(object):
def __init__(self):
self.__statusCode = "value bound in SUPERCLASS"
getStatusCode = property(lambda self: self.__statusCode)

class SubClass(SuperClass):
def __init__(self):
# SuperClass.__init__(self)
self.__statusCode = "value bound in SUBCLASS"

if __name__ == "__main__":
s = SubClass()
print s.getStatusCode
----------------------------------------------------------------

If I run this program, I get an exception (output wrapped by hand):

Traceback (most recent call last):
File "./xxx.py", line 14, in ?
print s.getStatusCode
File "./xxx.py", line 5, in <lambda>
getStatusCode = property(lambda self: self.__statusCode)
AttributeError: 'SubClass' object has no attribute \
'_SuperClass__statusCode'

Why is the lambda function attempting to access the superclass' attribute
and not the subclass' attribute? Can I make it not do that?

If I replace "__statusCode" with "_statusCode", the output is

value bound in SUBCLASS

as I want. However, "_statusCode" is then visible from the outside, as I
don't want.

Am I missing something about how Python works?

Is my problem more fundamental, like not understanding OO programming?

I'm able to RTFM if someone would provide a pointer.
Jul 18 '05 #1
3 6401

"Jules Dubois" <bo***@invalid.tld> wrote in message
news:1r*****************************@40tude.net...
[snip]
Why is the lambda function attempting to access the superclass' attribute
and not the subclass' attribute? Can I make it not do that?


Try this:

getStatusCode = property(lambda self: getattr(self,
'_%s__statusCode'%self.__class__.__name__))

HTH
Sean

Jul 18 '05 #2
Jules Dubois wrote:
I'm want to create a superclass with nothing but attributes and
properties. Some of the subclasses will do nothing but provide values for
the attributes.

(I'd also like to make sure (1) that the subclass provides actual values
for the attributes and (2) that no "client" module adds or removes
attributes or properties, but I don't know how to do those.)
You'll need a custom metaclass; you need to read up on this concept,
but these days you can find explanations on the net. Any class is an
instance of a metaclass -- the class statement implies a call to the
metaclass, which in turn means the MC's __new__ then __init__ as
in any other class-call (instantiation) -- and that call must provide and
initialize the class object.

Not sure what you mean by "client" module, but in general Python is
not about stopping Python programers from performing tasks -- so if
you see your task as one of placing inhibitions on other Pythonistas
who want to use your code, you're in for a fight. Still, you can do a good
job of ensuring that things don't happen _accidentally_, and that is
generally good enough -- a "malicious" other programmer is quite a
different kettle of fish, though.
Anyway, your problem has nothing to do with these difficult issues
(it's more of an issue of running before one can walk):
I don't understand what I'm doing wrong, or maybe what I want to do is
impossible. Here's a stripped down version of the code:

----------------------------------------------------------------
#! /usr/bin/python
class SuperClass(object):
def __init__(self):
self.__statusCode = "value bound in SUPERCLASS"
getStatusCode = property(lambda self: self.__statusCode)
This mangles the identifier __statusCode within class SuperClass,
giving _SuperClass__statusCode.
class SubClass(SuperClass):
def __init__(self):
# SuperClass.__init__(self)
self.__statusCode = "value bound in SUBCLASS"
But this mangles it within class SubClass, giving _SubClass__statusCode, a
different identifier. That's what leading __ is all about: giving an
identifier that strictly depends on the class where it's LEXICALLY found.
If you don't want that, don't use two leading underscores: use just one
(advisory indicator of privacy) and be happy. Or, you *CAN* simulate by
hand the mangling, though there's little point in so doing -- e.g., in
SuperClass, you can code:

def getStatusCode(self):
attr_name = '_%s__statusCode' % self.__class__.__name__
return getattr(self, attr_name)
statusCode = property(getStatusCode)

note that the leading get normally denotes an accessor method -- the
point of properties is having something that doesn't LOOK like a getter,
so naming one with a leading 'get' is quite peculiar.
Why is the lambda function attempting to access the superclass' attribute
and not the subclass' attribute? Can I make it not do that?
Sure.
If I replace "__statusCode" with "_statusCode", the output is

value bound in SUBCLASS

as I want. However, "_statusCode" is then visible from the outside, as I
don't want.
There is no way to make the value NOT "visible from the outside" -- WITH
the leading underscores, it's STILL visible, as "_SubClass__statusCode",
anyway. If you stashed the value away in a remote dict and encoded it
with strong cryptography, it would STILL be visible -- nothing stops a
halfway determined attacker from duplicating whatever way your superclass
uses to get at it. Treating "client code programmers" as enemies and your
task as one of fighting against them to stop them from "abusing" your
pristine design is not Python's strength -- indeed the tools you used to
have for this fight, rexec and Bastion, were recently removed as they did
not prove strong enough for this thankless task. In Python, you had better
think of all these mechanisms as ADVISORY "security" -- and then the
simple convention of the one leading underscore should be ample: anybody
who deliberately uses an identifier starting with a leading underscore is
knowingly going beyond the interface to the implementation, anyway. The
TWO leading underscores serve the specific purpose of allowing programmers
who code subclasses to blissfully ignore whatever private implementation
names the superclass has used for attributes, as it ensures against any
accidental name clashes -- using them for *communication* between base
and derived classes is weird, since they're mainly for *isolating* base from
derived classes.

Am I missing something about how Python works?

Is my problem more fundamental, like not understanding OO programming?

I'm able to RTFM if someone would provide a pointer.


Googling for:
Python metaclass
gives you plenty of material to chew on. I also suggest my presentation on
the subject, PDF slides at http://www.strakt.com/docs/ep03_meta.pdf .
Alex

Jul 18 '05 #3
On Mon, 22 Sep 2003 23:22:44 -0600
Jules Dubois <bo***@invalid.tld> wrote:
I'm want to create a superclass with nothing but attributes and properties.
Some of the subclasses will do nothing but provide values for the
attributes.
(I'd also like to make sure (1) that the subclass provides actual values
for the attributes and (2) that no "client" module adds or removes
attributes or properties, but I don't know how to do those.)
I don't understand what I'm doing wrong, or maybe what I want to do is
impossible. Here's a stripped down version of the code:


Question : why didn't you initialize your super class????
if you do it passing the values you want as arguments then you could have a code
like :
<PYTHON>
#! /usr/bin/python
class SuperClass(object):
def __init__(self,stat_code):
# self.__statusCode = "value bound in SUPERCLASS"
self.__statusCode = stat_code
getStatusCode = property(lambda self: self.__statusCode)
class SubClass(SuperClass):
def __init__(self):
self.__statusCode = "value bound in SUBCLASS"
SuperClass.__init__(self,self.__statusCode )
if __name__ == "__main__":
s = SubClass()
print s.getStatusCode
print
try :
print s.__statusCode
except :
print "cannot do that.. print s.__statusCode"
</PYTHON>

where you don't have private attributes visible and yet you have the values you
passed from the subclass..

NOTE : later on accessing those values from your sublass other than from the SuperClass initialization is other story...(setattribute,getattribute...or self.functions)
In your local python documentation.. read the tutorial section on classes:
/python2.2-doc/html/tut/node11.htm

Jul 18 '05 #4

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

Similar topics

28
by: Act | last post by:
Why is it suggested to not define data members as "protected"? Thanks for help!
4
by: p988 | last post by:
using System; using System.Windows.Forms; using System.Drawing; class MyForm : Form { MyForm () { Text = "Windows Forms Demo"; }
2
by: Andreas Klemt | last post by:
Hello, what is the difference between a) Protected WithEvents myClassName b) Protected myClassName Thanks, Andreas
3
by: Jordan Taylor | last post by:
I am confused about protected member functions and objects. Is there any particular advantage of declaring members protected?
4
by: Tina | last post by:
This is an issue regarding what exactly is accomplished by using "Protected" when defining a variable. It seems it does much more than just applying Protected status to a variable. I have an...
2
by: Rob Richardson | last post by:
Greetings! Consider the following: class CBase { public: CBase(); virtual ~CBase();
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.