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

Using properties

I have a class with a name attribute, which I want to modify using
property.The following code works just fine:

class Portfolio(object):

def __init__( self, name="Port1"):
self.name=name

def getname(self):
return self._name

def setname(self,newname="Port2"):
self._name=newname

name=property(getname,setname,None,None)

However, it no longer works if I modify getname and setname to

def getname(self):
return self.name

def setname(self,newname="Port2"):
self.name=newname

Why is it so critical to have getname and setname modify _name and not
name? The constructor does not make name a private attribute, so why do
getname and setname have to treat it as such?

Thomas Philips

Jul 19 '05 #1
6 1427

<tk****@hotmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
I have a class with a name attribute, which I want to modify using
property.The following code works just fine:

class Portfolio(object):

def __init__( self, name="Port1"):
self.name=name

def getname(self):
return self._name

def setname(self,newname="Port2"):
self._name=newname

name=property(getname,setname,None,None)

However, it no longer works if I modify getname and setname to
What does 'no longer works' mean? Do you get and exception and traceback?
If so, what?
def getname(self):
return self.name def setname(self,newname="Port2"):
self.name=newname
These both look like infinite loops. Did you got the related exceptions?
Why is it so critical to have getname and setname modify _name and not
name? The constructor does not make name a private attribute, so why do
getname and setname have to treat it as such?


I believe because getting and setting name calls getname and setname. The
initializer (not constructor) setting of name results in a call to setname.

Terry J. Reedy

Jul 19 '05 #2
tk****@hotmail.com wrote:
name=property(getname,setname,None,None)

However, it no longer works if I modify getname and setname to

def getname(self):
return self.name

def setname(self,newname="Port2"):
self.name=newname


That's because you're actually modifying the property in setname instead
of modifying the normal attribute. It's equivalent to doing:

def setname(self, newname="Port2"):
self.setname(newname)
Jul 19 '05 #3
tk****@hotmail.com wrote:
I have a class with a name attribute, which I want to modify using
property.The following code works just fine:

class Portfolio(object):

def __init__( self, name="Port1"):
self.name=name
This may not do what you think it does (see below)

def getname(self):
return self._name
def setname(self,newname="Port2"):
self._name=newname

name=property(getname,setname,None,None)

However, it no longer works if I modify getname and setname to

def getname(self):
return self.name

def setname(self,newname="Port2"):
what's the use of putting a default value here ?
self.name=newname
How could this work, since self.name is now a property object that calls
on setname() and getname() ?
Why is it so critical to have getname and setname modify _name and not
name?
because 'name' is how you named your property...
The constructor does not make name a private attribute,
Note that there is in fact no notion of private/public in Python (I mean
: in the language). The underscore stuff is nothing more than a convention.

Now you don't seem to understand what happens when __init__ is called.
Try this:

8<------------------------------------------------
class Portfolio(object):

def __init__( self, name="Port1"):
self.name=name
print "self._name is %s" % self._name
print "self.__class__.name is %s" % self.__class__.name

def _getname(self):
print "in getname"
return self._name

def _setname(self, newname):
print "in setname"
try:
print "self._name is %s" % self._name
except AttributeError, e:
print "got AttributeError %s" % e
print "when trying to access self._name"
self._name=newname

name=property(fget=_getname, fset=_setname)
print "in Portfolio class definition : name is %s" % name

p = Portfolio()
8<------------------------------------------------

As you can see, the 'name=property(...)' statement at the end of your
class definition is executed when the class definition is first eval'd
(this is when the code is loaded in the interpreter). So when __init__
is called, the statement 'self.name = name' does not create an instance
variable 'name', but calls the existing property, which in turn creates
the instance variable '_name'.
so why do
getname and setname have to treat it as such?


From a technical POV, we don't care if the attribute accessed by a
property is 'private' or whatever. The only thing is that it can't have
the same name as the property...

From a conceptual POV, it makes no sense (well, IMHO) to use a property
for a 'public' (by convention...) attribute. Either you want a property
(think : a computed attribute) and then you hide the implementation
details, or you're ok with a plain old 'public' attribute and then you
don't use a property.

BTW, this is also true of the setter and getter used by the property:
they are implementation details, and as such should not be exposed as
part of the interface.

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 19 '05 #4
Thanks for the help. I now understand it better. As Bruno points out, I
really don't need a property in this case, as my attribute is public,
and I will remove it.

Thomas Philips

Jul 19 '05 #5

<tk****@hotmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
Thanks for the help. I now understand it better. As Bruno points out, I
really don't need a property in this case, as my attribute is public,
and I will remove it.


As much to the point is that your name attribute is static in the sense of
being a fixed object between settings. Should you later want to make it
dynamic (or perhaps lazy) in the sense of being computed on demand, then
you can do so with property() *without* changing the external interface to
the class.

A third reason for property() is when you want to do something in addition
to the access, such as reporting the access to something else.

Terry J. Reedy

Jul 19 '05 #6
tk****@hotmail.com wrote:
Thanks for the help. I now understand it better. As Bruno points out, I
really don't need a property in this case, as my attribute is public,
and I will remove it.


Should you need it to be a property at a latter date, it's worth noting
that you can achieve what you were initially after by wrapping the
property's get/set around the objects '__dict__' attribute:

def getname(self): return self.__dict__['name']
def setname(self): self.__dict__['name'] =newname

Hope this helps.

-alex23

Jul 19 '05 #7

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

Similar topics

22
by: Bradley | last post by:
Has anyone else noticed this problem? I converted the back-end to A2000 and the performance problem was fixed. We supply a 97 and 2000 version of our software so we kept the backend in A97 to make...
11
by: Grasshopper | last post by:
Hi, I am automating Access reports to PDF using PDF Writer 6.0. I've created a DTS package to run the reports and schedule a job to run this DTS package. If I PC Anywhere into the server on...
9
by: Ben Dewey | last post by:
Project: ---------------------------- I am creating a HTTPS File Transfer App using ASP.NET and C#. I am utilizing ActiveDirectory and windows security to manage the permissions. Why reinvent...
1
by: Prasad Karunakaran | last post by:
I am using the C# DirectoryEntry class to retrieve the Properties of an user object in the Active Directory. I need to get the First Name and Last Name as properties. I know it is not supported...
0
by: Brian Young | last post by:
Hi all. I'm using the Property Grid control in a control to manage a windows service we have developed here. The windows service runs a set of other jobs that need to be managed. The control...
13
by: Andy Baxter | last post by:
Can anyone recommend a good online guide to using objects in javascript? The book I bought (DHTML Utopia) suggests using objects to keep the code clean and stop namespace clashes between different...
1
by: sudhapadmas | last post by:
Hello netters, I was trying to create a virtual directory in IIS using the following code: System.EnterpriseServices.Internal.IISVirtualRoot vr = new...
1
by: Yewen Tang | last post by:
I have a schema file datamodel.xsd, element "properties" is declared as a type of "baseProperty". The schema file also defines "derivedProperty" is a derived type of "baseProperty". <?xml...
0
by: =?Utf-8?B?Um9i?= | last post by:
I've a requirement to monitor when certain applications are started. I'm using WMI called from VS Stusio 2005 in VB to trap Excel and Word starting. I've written the following console application...
0
by: dixonjm | last post by:
Hi, I have a master page & various pages that will use this master page. Each content page will have a CSS & JS file which will be named the same as the content page. When I try to load the CSS...
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:
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
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...
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
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...

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.