473,809 Members | 2,736 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

inherit and overwrite a property (better its method call)

hi,
i am tinkering with properties of new style classes:

class Base(object):

def m(self):
return 'p of Base'
p = property(m)

class Sub(Base):
def m(self):
return 'p of Sub'

b = Base()
print b.p # prints 'p of Base'

s = Sub()
print s.p # prints 'p of Base'!?

i was thinking s.p would use the method m of class Sub and not Base. but
this does not work, both properties "p" of Base and Sub use method m of
baseclass Base.

so it seems i cannot overwrite the method p calls to get its value
without actually repeating the property definition in every subclass, or
is there a way? the following does work but i want to get rid of the
second p = property(m)...

class Sub(Base):
def m(self):
return 'p of Sub'
p = property(m)

print b.p # prints 'p of Base'
s = Sub()
print s.p # prints 'p of Sub'

am i missing something?
thanks for any advice
chris

Jul 18 '05 #1
2 2328
chris wrote:
hi,
i am tinkering with properties of new style classes:

class Base(object):

def m(self):
return 'p of Base'
p = property(m)

class Sub(Base):
def m(self):
return 'p of Sub'

b = Base()
print b.p # prints 'p of Base'

s = Sub()
print s.p # prints 'p of Base'!?

i was thinking s.p would use the method m of class Sub and not Base. but
this does not work, both properties "p" of Base and Sub use method m of
baseclass Base.

so it seems i cannot overwrite the method p calls to get its value
without actually repeating the property definition in every subclass, or
is there a way? the following does work but i want to get rid of the
second p = property(m)...

class Sub(Base):
def m(self):
return 'p of Sub'
p = property(m)

print b.p # prints 'p of Base'
s = Sub()
print s.p # prints 'p of Sub'

am i missing something?


I don't think so. Anyway, I have been tinkering too, and here's what I've
come up with so far:

class inheritableprop erty(property):
""" property with overridable accessor functions """

def funcByName(cls, fn):
# helper func
if fn is None: return None
result = getattr(cls, fn.__name__, None)
assert result is None or callable(result )
return result

class typewithinherit ableproperties( type):
def __init__(cls, name, bases, dict):
super(typewithi nheritableprope rties, cls).__init__(n ame, bases,
dict)
# replace inheritable properties with new instances where
# the accessors are determined by a name lookup in the actual class
for name in dir(cls):
a = getattr(cls, name)
if isinstance(a, inheritableprop erty):
setattr(cls, name, inheritableprop erty(
funcByName(cls, a.fget),
funcByName(cls, a.fset),
funcByName(cls, a.fdel)
))

class A(object):
__metaclass__ = typewithinherit ableproperties
def geta(self): return "A.a"
a = inheritableprop erty(geta)

class B(A):
def geta(self): return "B.a"

class C(A): pass
class D(B): pass

print A().a
print B().a
print C().a
print D().a

http://www.python.org/2.2/descrintro.html might also be of interest for you.
It has an example of properties based on naming conventions (class
autoprop).

Peter

Jul 18 '05 #2
Peter Otten wrote:
chris wrote:
<snip>
http://www.python.org/2.2/descrintro.html might also be of interest for you.
It has an example of properties based on naming conventions (class
autoprop).


I ran into the same problem, and coded a property of my own. The problem
is that property() holds the actual functions, so when you overwrite
them in the subclass, the property doesn't know about it. The approach
below only saves the name of the function, and delays the lookup of the
actual function when needed.
class subclass_proper ty(object):
'''Creates an property just like a built-in property, except that the
functions that are part of the property can be changed in a subclass.
'''

def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget_name = fget and fget.__name__
self.fset_name = fset and fset.__name__
if isinstance(fdel , str):
doc = fdel
fdel = None
self.fdel_name = fdel and fdel.__name__
self.doc = doc or ''
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget_name is None:
raise AttributeError, "unreadable attribute"
fget = getattr(obj, self.fget_name)
return fget()
def __set__(self, obj, value):
if self.fset_name is None:
raise AttributeError, "can't set attribute"
fset = getattr(obj, self.fset_name)
fset(value)
def __delete__(self , obj):
if self.fdel_name is None:
raise AttributeError, "can't delete attribute"
fdel = getattr(obj, self.fdel_name)
fdel()
def __repr__(self):
p = []
if self.fget_name:
p.append(self.f get_name)
if self.fset_name:
p.append(self.f set_name)
if self.fdel_name:
p.append(self.f del_name)
if self.doc:
p.append(repr(s elf.doc))
return 'action.propert y(%s)' % ', '.join(p)

HTH,
Nicodemus.
Jul 18 '05 #3

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

Similar topics

5
7496
by: Gord | last post by:
Hello, If you set the flag for an overwrite prompt using the 'Save' common dialog, how do you read the response when the user clicks the Yes or No in the 'overwrite' message box? Everything I've read explains about setting the flag to bring up the overwrite prompt message box, but there's no explanation on how to read the response to it. It appears that clicking the Yes option doesn't actually overwrite the old file, so I assume I'm...
3
3139
by: Christian Dieterich | last post by:
Hi, I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example and two workarounds, but I feel they are not really good solutions. Does somebody have any ideas how to inherit the data attributes and the methods of a class without calling it's constructor over and over again? Thank,
5
7146
by: Mike L | last post by:
This is my first attempt at inheriting a class. I want to inherit textbox class to my derived class ClassNum. ClassNum will override the TextChanged, Leave, KeyPress and Enter methods. So, far I was able to inherit the textbox class to ClassNum, but I get errors when I try to override the methods. class ClassNum : System.Windows.Forms.TextBox {
7
1756
by: Frank | last post by:
Hi, a question probably asked before, but I can't find the answers. Base class X, classes A, B and C inherit class X. In class A I do not want to inherit property (or function or method) P1. Possible? How? Thanks in advance Frank
12
5933
by: Mark Fink | last post by:
I wrote a Jython class that inherits from a Java class and (thats the plan) overrides one method. Everything should stay the same. If I run this nothing happens whereas if I run the Java class it says: usage: java fit.FitServer host port socketTicket -v verbose I think this is because I do not understand the jython mechanism for inheritance (yet).
3
1971
by: Kai Kuehne | last post by:
Hi list! It is possible to overwrite only one function with the property-function? x = property(getx, setx, delx, 'doc') I just want to overwrite setx, but when I set the others to None, I can't read and del the member. Any ideas or is this not possible? Thank you! Kai
19
2452
by: zzw8206262001 | last post by:
Hi,I find a way to make javescript more like c++ or pyhon There is the sample code: function Father(self) //every contructor may have "self" argument { self=self?self:this; //every class may have this statement self.hello = function() {
3
6436
by: MisterPete | last post by:
I've run into this issue a couple of times. I want to inherit from a class in order to extend it's functionality. The problem is that the class is defined in c in a shared library and doesn't seem to be designed so that it will allow inheritance (no __class__ defined, etc). For example the Client object from pysvn. import pysvn class MyClient(pysvn._pysvn._Client): pass Traceback (most recent call last): File "<stdin>",...
2
6468
by: hzgt9b | last post by:
I know how to overwrite a function. Normally this is what I would do: function someFunction() { /* orig definition here */ } //later in the execution stream I would do... someFunction = function () { /* overwrite function definition */ } The above works fine for me even when someFunction is originally defined in a seperate frame other than the code that overwrites it (obviously on the same domain). What I don't know how to-do is...
0
9721
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
9601
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
10635
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
10376
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
9198
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
6881
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
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3013
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.