473,757 Members | 10,007 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"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(obje ct):
def __init__(self):
self.__statusCo de = "value bound in SUPERCLASS"
getStatusCode = property(lambda self: self.__statusCo de)

class SubClass(SuperC lass):
def __init__(self):
# SuperClass.__in it__(self)
self.__statusCo de = "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.__statusCo de)
AttributeError: 'SubClass' object has no attribute \
'_SuperClass__s tatusCode'

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 "__statusCo de" with "_statusCod e", the output is

value bound in SUBCLASS

as I want. However, "_statusCod e" 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 6424

"Jules Dubois" <bo***@invalid. tld> wrote in message
news:1r******** *************** ******@40tude.n et...
[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__statusCod e'%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(obje ct):
def __init__(self):
self.__statusCo de = "value bound in SUPERCLASS"
getStatusCode = property(lambda self: self.__statusCo de)
This mangles the identifier __statusCode within class SuperClass,
giving _SuperClass__st atusCode.
class SubClass(SuperC lass):
def __init__(self):
# SuperClass.__in it__(self)
self.__statusCo de = "value bound in SUBCLASS"
But this mangles it within class SubClass, giving _SubClass__stat usCode, 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(s elf):
attr_name = '_%s__statusCod e' % self.__class__. __name__
return getattr(self, attr_name)
statusCode = property(getSta tusCode)

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 "__statusCo de" with "_statusCod e", the output is

value bound in SUBCLASS

as I want. However, "_statusCod e" 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__sta tusCode",
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(obje ct):
def __init__(self,s tat_code):
# self.__statusCo de = "value bound in SUPERCLASS"
self.__statusCo de = stat_code
getStatusCode = property(lambda self: self.__statusCo de)
class SubClass(SuperC lass):
def __init__(self):
self.__statusCo de = "value bound in SUBCLASS"
SuperClass.__in it__(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...(setatt ribute,getattri bute...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
3426
by: Act | last post by:
Why is it suggested to not define data members as "protected"? Thanks for help!
4
7350
by: p988 | last post by:
using System; using System.Windows.Forms; using System.Drawing; class MyForm : Form { MyForm () { Text = "Windows Forms Demo"; }
2
5073
by: Andreas Klemt | last post by:
Hello, what is the difference between a) Protected WithEvents myClassName b) Protected myClassName Thanks, Andreas
3
6723
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
1826
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 ascx control named HeadingBar. I have dragged it onto an aspx page. If I use the following statement..... Dim HeadingBar1 as HeadingBar
2
1653
by: Rob Richardson | last post by:
Greetings! Consider the following: class CBase { public: CBase(); virtual ~CBase();
0
9489
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9906
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9885
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
8737
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
7286
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
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.