473,795 Members | 3,457 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overriding properties

Why does the following print "0 0" instead of "0 1"? What is the
canonical way to rewrite it in order to get what I obviously expect?

class C(object):
__val = 0
def set_value(self, val):
if val < 0 : self.__val = 0
else : self.__val = val
def get_value(self) :
return self.__val
value = property(get_va lue, set_value)

class CC(C):
def set_value(self, val):
if val < 0: self.__val = 1
else : self.__val = val

c = C()
cc = CC()
c.value = -1
cc.value = -1
print c.value, cc.value

Thanks in advance
/npat
Jul 18 '05 #1
2 1720
Nick Patavalis wrote:
Why does the following print "0 0" instead of "0 1"? What is the
canonical way to rewrite it in order to get what I obviously expect?

class C(object): <snip> value = property(get_va lue, set_value)

class CC(C):
def set_value(self, val): <snip> c.value = -1
cc.value = -1
print c.value, cc.value


The problem is that the names get_value and set_value are evaluated only
once: when class C is first defined. The property has no knowledge of
(or interest in) the fact that a different function named set_value has
been defined.

There are several ways to fix it. The simplest would be to create a new
property object in CC's definition:

class CC(C):
def set_value(self, val):
if val < 0:
self.__val = 1
else:
self.__val = val
value = property(C.get_ value, set_value)

But an easier, more flexible method would be to use a metaclass which
automatically adds properties for specially-named methods. One example
of such a metaclass is autoprop from Guido van Rossum's descrintro
essay; see <URL:http://www.python.org/2.2.3/descrintro.html >.
Jul 18 '05 #2
There are several ways to fix it. The simplest would be to create a new property object in CC's definition:

class CC(C):
def set_value(self, val):
if val < 0:
self.__val = 1
else:
self.__val = val
value = property(C.get_ value, set_value)
It won't fix because __val is defined as a class variable in C, but as
an instance variable in CC. The set_value method creates a new __val. A
typical Python pitfall. C.get_value would still return _C__val.
But an easier, more flexible method would be to use a metaclass which automatically adds properties for specially-named methods. One example of such a metaclass is autoprop from Guido van Rossum's descrintro
essay; see <URL:http://www.python.org/2.2.3/descrintro.html >.


Yes, but i dislike it either. This powerfull metaclass approach
obscures the property creation right in the place. And it supports the
tendency to create fat frameworks. A few weeks ago i talked to someone
who avoided propertys completely because they seemed to Javaesque to
him. I first agreed and understood his ranting about this awkward
get_bla, set_blubb stuff. Then I rembebered that the property()
function is just a descriptor-creator and one can easily wrap around it
for simplification.

So i defined defprop()

def defprop(name, default = None, modify=None, check=None, types=[]):

name = "__"+name
def get(obj):
if not hasattr(obj,nam e):
setattr(obj,nam e, default)
return getattr(obj,nam e)

def set(obj,value):
if types:
if not True in [isinstance(valu e,t) for t in types]:
raise TypeError, "Can't assign %s to property
%s."%(value,nam e[2:])
if check:
if not check(value):
raise TypeError, "Can't assign %s to property
%s."%(value,nam e[2:])
if modify:
setattr(obj,nam e,modify(value) )
else:
setattr(obj,nam e,value)

return property(get,se t,None)
I left out to define delete. It was for demonstration purposes only.
Now define Your own classes:

class X(object):
a = defprop("a")
b = defprop("b",typ es=(tuple,list) )
c = defprop("c",che ck = lambda x:hasattr(x,"__ len__"))
d = defprop("d",def ault=0)

class XX(X):
def set_d(val):
if val<0:
return 1
return val

d = defprop("d",def ault=0,modify=s et_d) # overwrite d

It would be nice also to refuse the redundant naming a = defprop("a")
and write
a = defprop() instead. But it's actually not possible at the moment (
or only with deep introspection ).

Session on:
x = X()
x.d 0 xx = XX()
xx.d 0 xx.d = -1
xx.d

1

Ciao
Kay

Jul 18 '05 #3

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

Similar topics

0
2201
by: Nigel Sampson | last post by:
ey all, I'm in the process of creating a method of tracking whenever an objects properties are changed. Since its not possible to alter existing types I decided to used a proxy generated using Reflection.Emit which inherits from the object needed Person p = (Person)ProxyBuilder.Construct(typeof(Person));
8
2267
by: Edward Diener | last post by:
Is it possible for a derived class to override a property and/or event of its base class ?
10
5210
by: muscha | last post by:
I don't get it. What's the main differences between overriding a base class's methods vs. hiding them? Thanks, /m
4
1933
by: ORi | last post by:
Hi all ! There's a question I've been bothering for a while: I'm actually developing architectural frameworks for application developing and I think virtual methods, although needed because of the flexibility they introduce (flexibility really needed in framework developing), are often a nuisance for final developers. They don't like them because they never know if base class must be called and where should they place the call if...
1
1936
by: Anders Borum | last post by:
Hello! I have a framework where all objects are uniquely identified by a GUID (Global Unique Identifier). The objects are used in conjunction with lots of hashtables and I was thinking, that overriding the GetHashCode base method (inherited from object) was a good idea. public abstract class CmsObjectNode : CmsObject, IXml { private Guid cmsObjectID = Guid.NewGuid();
2
3605
by: ESPNSTI | last post by:
Hi, I'm very new to C# and .Net, I've been working with it for about a month. My experience has been mainly with Delphi 5 (not .Net). What I'm looking for is for a shortcut way to override a property without actually having to reimplement the get and set methods. In other words, override the the property without changing the functionality of the base property and without explicitly having to reimplement the get and set methods to make it do...
17
2920
by: Bob Weiner | last post by:
What is the purpose of hiding intead of overriding a method? I have googled the question but haven't found anything that makes any sense of it. In the code below, the only difference is that when the Poodle is upcast to the Dog (in its wildest dreams) it then says "bow wow" where the bernard always says "woof" (see code). Basically, it appears that I'm hiding the poodle's speak method from everything except the poodle. Why would I...
2
1653
by: project | last post by:
Hi every body, Any body can help me the following doubts? 1. what is constructor? 2. what is destructor? 3. what is overriding function. 4. different between structure and array 5. what is objected oriented
18
4751
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class instance. However, the 'indexof' is never calling my overloaded, overrides Equals method. Here is the...
3
2376
by: Dan Jacobson | last post by:
Let's say all one can do to override a document's link colors, <a href="FAQ.aspx"><font color="#0000ff">FAQ</font></a> is inject things like: <a href="FAQ.aspx"><span style="color:green"><font color="#0000ff">FAQ</font></span></a> only at the <A></Aedges (as I have done above setting WWWOFFLE's anchor-cached-begin value.) Which, depending on DOCTYPE, is not strong enough to override the most inner <fontwhen view in firefox. Nor does...
0
9519
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
10437
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10214
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...
0
9042
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...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3723
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
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.