473,785 Members | 2,310 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

override a property

Is there a way to override a data property in the instance? Do I need to create
another class with the property changed?
--
Robin Becker

Oct 17 '05 #1
18 4763
No, you can just do it on the fly. You can even create properties
(attributes) on the fly.

class Dummy:
property = True

d = Dummy()
d.property = False
d.new = True

Stani
--
SPE - Stani's Python Editor http://pythonide.stani.be

Oct 17 '05 #2
Robin Becker a écrit :
Is there a way to override a data property in the instance? Do I need to
create another class with the property changed?


Do you mean attributes or properties ?
Oct 17 '05 #3
On Mon, 17 Oct 2005 18:52:19 +0100, Robin Becker <ro***@reportla b.com> wrote:
Is there a way to override a data property in the instance? Do I need to create
another class with the property changed?

How do you need to "override" it? Care to create a toy example with a
"wish I could <override action> here" comment line? ;-)

Regards,
Bengt Richter
Oct 17 '05 #4
On 17 Oct 2005 11:13:32 -0700, "SPE - Stani's Python Editor" <sp**********@g mail.com> wrote:
No, you can just do it on the fly. You can even create properties
(attributes) on the fly.

class Dummy:
property = True

d = Dummy()
d.property = False
d.new = True

a simple attribute is not a property in the sense Robin meant it,
and a "data property" is even more specific. See

http://docs.python.org/ref/descriptor-invocation.html

also
help(property)

Help on class property in module __builtin__:

class property(object )
| property(fget=N one, fset=None, fdel=None, doc=None) -> property attribute
|
| fget is a function to be used for getting an attribute value, and likewise
| fset is a function for setting, and fdel a function for del'ing, an
| attribute. Typical use is to define a managed attribute x:
| class C(object):
| def getx(self): return self.__x
| def setx(self, value): self.__x = value
| def delx(self): del self.__x
| x = property(getx, setx, delx, "I'm the 'x' property.")
|
Regards,
Bengt Richter
Oct 17 '05 #5
Bruno Desthuilliers wrote:
Robin Becker a écrit :
Is there a way to override a data property in the instance? Do I need
to create another class with the property changed?

Do you mean attributes or properties ?


I mean property here. My aim was to create an ObserverPropert y class
that would allow adding and subtracting of set/get observers. My current
implementation works fine for properties on the class, but when I need
to specialize an instance I find it's quite hard.

--
Robin Becker
Oct 18 '05 #6
Robin Becker wrote:
Bruno Desthuilliers wrote:
Robin Becker a écrit :
Is there a way to override a data property in the instance? Do I need
to create another class with the property changed?
Do you mean attributes or properties ?

I mean property here.


Ok, wasn't sure... And sorry, but I've now answer.
My aim was to create an ObserverPropert y class
that would allow adding and subtracting of set/get observers.
Could you elaborate ? Or at least give an exemple ?
My current
implementation works fine for properties on the class, but when I need
to specialize an instance I find it's quite hard.


--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Oct 18 '05 #7
Robin Becker <ro***@SPAMREMO VEjessikat.fsne t.co.uk> wrote:
Bruno Desthuilliers wrote:
Robin Becker a écrit :
Is there a way to override a data property in the instance? Do I need
to create another class with the property changed?


Do you mean attributes or properties ?


I mean property here. My aim was to create an ObserverPropert y class
that would allow adding and subtracting of set/get observers. My current
implementation works fine for properties on the class, but when I need
to specialize an instance I find it's quite hard.


A property is an 'overriding descriptor', AKA 'data descriptor', meaning
it "captures" assignments ('setattr' kinds of operations), as well as
accesses ('getattr' kinds), when used in a newstyle class. If for some
reason you need an _instance_ to bypass the override, you'll need to set
that instance's class to one which has no overriding descriptor for that
attribute name. A better design might be to use, instead of the builtin
type 'property', a different custom descriptor type that is specifically
designed for your purpose -- e.g., one with a method that instances can
call to add or remove themselves from the set of "instances overriding
this ``property''" and a weak-key dictionary (from the weakref module)
mapping such instances to get/set (or get/set/del, if you need to
specialize "attribute deletion" too) tuples of callables.
Alex
Oct 18 '05 #8
bruno modulix wrote:
......

Could you elaborate ? Or at least give an exemple ? ......
in answer to Bengt & Bruno here is what I'm sort of playing with. Alex suggests
class change as an answer, but that looks really clunky to me. I'm not sure what
Alex means by
A better design might be to use, instead of the builtin
type 'property', a different custom descriptor type that is specifically
designed for your purpose -- e.g., one with a method that instances can
call to add or remove themselves from the set of "instances overriding
this ``property''" and a weak-key dictionary (from the weakref module)
mapping such instances to get/set (or get/set/del, if you need to
specialize "attribute deletion" too) tuples of callables.


I see it's clear how to modify the behaviour of the descriptor instance, but is
he saying I need to mess with the descriptor magic methods so they know what
applies to each instance?
## my silly example
class ObserverPropert y(property):
def __init__(self,n ame,observers=N one,validator=N one):
self._name = name
self._observers = observers or []
self._validator = validator or (lambda x: x)
self._pName = '_' + name
property.__init __(self,
fset=lambda inst, value: self.__notify_f set(inst,value) ,
)

def __notify_fset(s elf,inst,value) :
value = self._validator (value)
for obs in self._observers :
obs(inst,self._ pName,value)
inst.__dict__[self._pName] = value

def add(self,obs):
self._observers .append(obs)

def obs0(inst,pName ,value):
print 'obs0', inst, pName, value

def obs1(inst,pName ,value):
print 'obs1', inst, pName, value

class A(object):
x = ObserverPropert y('x')

a=A()
A.x.add(obs0)

a.x = 3

b = A()
b.x = 4

#I wish I could get b to use obs1 instead of obs0
#without doing the following
class B(A):
x = ObserverPropert y('x',observers =[obs1])

b.__class__ = B

b.x = 7
--
Robin Becker

Oct 18 '05 #9
Robin Becker wrote:
Is there a way to override a data property in the instance? Do I need to create
another class with the property changed?
--
Robin Becker


It is possible to decorate a method in a way that it seems like
property() respects overridden methods. The decorator cares
polymorphism and accesses the right method.

def overridable(f):
def __wrap_func(sel f,*args,**kwd):
func = getattr(self.__ class__,f.func_ name)
if func.func_name == "__wrap_fun c":
return f(self,*args,** kwd)
else:
return func(self,*args ,**kwd)
return __wrap_func
class A(object):
def __init__(self, x):
self._x = x

@overridable
def get_x(self):
return self._x

x = property(get_x)

class B(A):

def get_x(self):
return self._x**2

class C(B):pass
a = A(7)
a.x 7 b = B(7)
b.x 49 c = C(7)
c.x

49

Oct 18 '05 #10

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

Similar topics

7
2074
by: Thomas Kehl | last post by:
Hello. I provided a class, which derives from the class DataView. The only thing, which I would like to do in this class am to overwrite the Property COUNT. I wars it however simply not. I get always following message from the compiler, although COUNT of the DataView (according to MSDN) is virtual. the element ' System.Data.DataView.Count.get ' cannot be overwritten, because as virtually, abstract or do not overwrite it is marked Can...
5
5919
by: Eric Johannsen | last post by:
I have a simple object that inherits from CollectionBase and overrides the Count property: namespace MyTest { public class CollTest : System.Collections.CollectionBase { public override int Count { get { return 0; }
5
6852
by: Darius | last post by:
I'm writing here in hopes that someone can explain the difference between the new and virtual/override keywords in C#. Specifically, what is the difference between this: public class Window { public void Draw() { Console.WriteLine("The WINDOW Draw method is running!");
7
6450
by: Dave Y | last post by:
I am a newbie to C# and am having trouble trying to override a ListView property method. I have created a new class derived from the Forms.Listview and I cannot figure out the syntax to override ListView.Items.Add(), . I see that it is a virtual method so it should be easy to do. If anyone can help I would appreciate it greatly. I can do what I need to do in a different way this would just make everything significantly cleaner and eaasier...
1
5340
by: Å krat Bolfenk | last post by:
How can I override property in C++/CLI. Well I know how to override when the input and output types are the same (and number) ..., but I would like the derived (overridden) property to return different type than base. Thanks
8
5498
by: bdeviled | last post by:
I am deploying to a web environment that uses load balancing and to insure that sessions persist across servers, the environment uses SQL to manage sessions. The machine.config file determines how all applications will use sessions and to insure that all application use this method, the session properties cannot be overriden. Within the sessionstate tags, the webadmin (upon my request)r emoved the property for timeout, hoping that...
4
1996
by: R. MacDonald | last post by:
Hello, Group, I have been curious about a statement I see occasionally in the VB (v2003) help. Sometimes the information about a property will indicate that it is overridable, and I have been making use of this. Sometimes there is also a statement such as: "You are not required to override both the get and set methods of the .... property; you can override only one if needed."
14
33291
by: Dave Booker | last post by:
It looks like the language is trying to prevent me from doing this sort of thing. Nevertheless, the following compiles, and I'd like to know why it doesn't work the way it should: public class ComponentA { static string s_name = "I am the root class."; public string Name { get {return s_name;} } }
1
3128
by: Joshua | last post by:
I'm creating a web control that has an image and a text box. I would like to then override the Visible and Text property of the usercontrol, so when you reference the visible property of the user control it only set the visible property of the textbox. When i call these newly created property I get the following error: Object reference not set to an instance of an object. Does anybody have any idea? Thank you.
0
9647
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
9485
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
10356
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
10161
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
10098
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
9958
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8986
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
7506
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...
1
4058
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

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.