473,583 Members | 3,386 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Default attribute in base class precludes delegation

Hi

In the following code sample, I have:
- a Worker class, which could have a lot of methods and attributes. In
particular, it has a 'bar' attribute. This class can be modified as needed.
- a Base class (old-style) which defines a default class attribute 'bar'
too. I can't modify the source code of this class. Note that Workes does
not inherit from Base.
- a Derived class which must inherit from Base and is a wrapper around
Worker: it contains a Worker instance and delegates almost anything to it.
This class can be modified as needed too.

For most attributes, as they are not found in the Derived instance's dict,
__getattr__ is called and the attribute is retrieved from the Worker instance.
But for the 'bar' attribute, it is found in the Base class and just the
default value is returned. __getattr__ is never called.
I need to avoid this, and return Worker instance's value instead of Base's
default value.
That is, in the last line of the example, I want: d.bar == 'Hello'
How could it be done?

--- cut ---
# This class does the "real" work and I can modify it as needed
class Worker:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar

# This is just a base class from which I must inherit but I can't modify it
class Base:
bar = None

# This is a wrapper for Worker and I can modify it.
# I want to get most attributes from Worker class
# but for 'bar' I always get the default from Base,
# its declaration there effectively hides the attribute
# from the delegated Worked instance.
class Derived(Base):
def __init__(self, worker):
self.worker = worker

def __getattr__(sel f, name):
return getattr(self.wo rker, name)

w = Worker(1234, 'Hello')
print 'w.foo', w.foo # prints 1234
print 'w.bar', w.bar # prints Hello
d = Derived(w)
print 'd.foo',d.foo # prints 1234
print 'd.bar',d.bar # prints None, I want to get Hello

--- cut ---

Gabriel Genellina
Softlab SRL
Jul 18 '05 #1
2 2026
On Fri, 19 Dec 2003 00:44:28 -0300, Gabriel Genellina <ga*********@so ftlab.com.ar> wrote:
Hi

In the following code sample, I have:
- a Worker class, which could have a lot of methods and attributes. In
particular, it has a 'bar' attribute. This class can be modified as needed.
- a Base class (old-style) which defines a default class attribute 'bar'
too. I can't modify the source code of this class. Note that Workes does
not inherit from Base.
- a Derived class which must inherit from Base and is a wrapper around
Worker: it contains a Worker instance and delegates almost anything to it.
This class can be modified as needed too. In what sense a "wrapper"?
For most attributes, as they are not found in the Derived instance's dict,
__getattr__ is called and the attribute is retrieved from the Worker instance. Why do you (think you) need an explicit __getattr__ ? Usually there's better ways.
But for the 'bar' attribute, it is found in the Base class and just the
default value is returned. __getattr__ is never called.
I need to avoid this, and return Worker instance's value instead of Base's
default value.
That is, in the last line of the example, I want: d.bar == 'Hello'
How could it be done?

--- cut ---
# This class does the "real" work and I can modify it as needed
class Worker: class Worker(object): def __init__(self, foo, bar):
self.foo = foo
self.bar = bar

# This is just a base class from which I must inherit but I can't modify it
class Base:
bar = None

# This is a wrapper for Worker and I can modify it.
# I want to get most attributes from Worker class
# but for 'bar' I always get the default from Base,
# its declaration there effectively hides the attribute
# from the delegated Worked instance.
class Derived(Base): class Derived(Worker, Base):
"""never mind any methods at this point yet"""
def __init__(self, worker):
self.worker = worker

def __getattr__(sel f, name):
return getattr(self.wo rker, name)

w = Worker(1234, 'Hello')
print 'w.foo', w.foo # prints 1234
print 'w.bar', w.bar # prints Hello
d = Derived(w) d = Derived(6578, 'Goodbye')
print 'd.foo',d.foo # prints 1234
print 'd.bar',d.bar # prints None, I want to get Hello

--- cut ---


Does this do anything for you? (you could inherit differently than below too, of course)

====< genellina.py >============== =============== =============== =============== ==============
# This class does the "real" work and I can modify it as needed
class Worker(object):
def __init__(self, foo, bar):
print 'Worker init: Initializing %s instance' % self.__class__. __name__
self.foo = foo
self.bar = bar

# This is just a base class from which I must inherit but I can't modify it
class Base:
def __init__(self,* args, **kw): print 'Base init:', args, kw
bar = None
baz = 'Base baz'

# This is a wrapper for Worker and I can modify it.
# I want to get most attributes from Worker class
##### why not just inherit them from ^^^^^^^^^^^^ ?
# but for 'bar' I always get the default from Base,
# its declaration there effectively hides the attribute
# from the delegated Worked instance.

class Derived(Worker, Base):
"""dummy until something to do"""

if __name__ == '__main__':
w = Worker(1234, 'Hello')
print 'w.foo of %s instance: %s' %(w.__class__._ _name__, w.foo) # prints 1234 now
print 'w.bar of %s instance: %s' %(w.__class__._ _name__, w.bar) # prints Hello now
d = Derived(5678, 'Goodbye') #w)
print 'd.foo of %s instance: %s' %(d.__class__._ _name__, d.foo) # prints 5678 now
print 'd.bar of %s instance: %s' %(d.__class__._ _name__, d.bar) # prints Goodbye now
print 'd.baz of/via %s instance: %s' %(d.__class__._ _name__, d.baz)
d.baz = 'd instance baz'
print 'd.baz of/via %s instance: %s' %(d.__class__._ _name__, d.baz)
=============== =============== =============== =============== =============== =============== ===

Result:

[21:52] C:\pywk\clp>gen ellina.py
Worker init: Initializing Worker instance
w.foo of Worker instance: 1234
w.bar of Worker instance: Hello
Worker init: Initializing Derived instance
d.foo of Derived instance: 5678
d.bar of Derived instance: Goodbye
d.baz of/via Derived instance: Base baz
d.baz of/via Derived instance: d instance baz

Or do you actually need to have different unknown types of workers so you can't inherit?

Regards,
Bengt Richter
Jul 18 '05 #2
At 19/12/2003 05:41, you wrote:
- a Derived class which must inherit from Base and is a wrapper around
Worker: it contains a Worker instance and delegates almost anything to it.
This class can be modified as needed too.In what sense a "wrapper"?


In fact it's an Adapter: it contains a reference to the Worker -and
delegates most method calls to it- also providing the interfase expected
from Base.
For most attributes, as they are not found in the Derived instance's dict,
__getattr__ is called and the attribute is retrieved from the Worker

instance.
Why do you (think you) need an explicit __getattr__ ? Usually there's
better ways.


How?
class Derived(Worker, Base):
"""dummy until something to do"""

Or do you actually need to have different unknown types of workers so you
can't inherit?


Oh, thanks but that won't work. There are many types of Workers, chosen at
run time, that's why I can't simply inherit and have to use delegation.
Gabriel Genellina
Softlab SRL
Jul 18 '05 #3

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

Similar topics

4
2929
by: Lénaïc Huard | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I've some namespace problems when defining default values for attributes. My problem seems to come from the fact that the attributes are defined in a different namespace from the element.
5
1463
by: Russell Warren | last post by:
I just ran across a case which seems like an odd exception to either what I understand as the "normal" variable lookup scheme in an instance/object heirarchy, or to the rules regarding variable usage before creation. Check this out: >>> class foo(object): .... I = 1 .... def __init__(self): .... print self.__dict__ .... ...
0
2815
by: Techotsav | last post by:
Hi guys I do have following class structure xxx.RoleManagement : xxx.RMUser. xxx.RMUser : System.web.ui.page These classes are added in solution as different project. Now what i am trying is to change .aspx page's base class from default system.web.ui.page to xxx.rolemanagement. But it is throwing following
8
1977
by: Jackson | last post by:
I want a class that will determine its base class by the argument passed in. What I am about to write _does_not_work_, but it shows what I am trying to do. class ABC(some_super): def __init__(self,some_super): some_super.__init__(self) if some_super == list: self.append('ABC')
1
1978
by: chris.bahns | last post by:
Hello All, I am fairly new to creating custom attributes, and want to get a better feel for how they should be named. We have a class hierarchy, with a base class called "SequenceCommand". This class has a couple static functions and an embedded class, all of which are referenced in code like "SequenceCommand.Create()" or...
47
3988
by: Larry Smith | last post by:
I just read a blurb in MSDN under the C++ "ref" keyword which states that: "Under the CLR object model, only public single inheritance is supported". Does this mean that no .NET class can ever support multiple inheritance. In C++ for instance I noticed that the compiler flags an error if you use the "ref" keyword on a class with multiple...
1
3393
by: mrstephengross | last post by:
I've got a Base class with an attribute "foo" (of type Foo), and a Derived class (derived from Base). In Derived's constructor, I try to refer to Base.foo, but python complains: AttributeError: class Base has no attribute 'foo' Any ideas? (code below) === CODE === #!/usr/bin/python
7
1439
by: George Sakkis | last post by:
A situation that often comes up is having to initialize several instance attributes that accept a default value. For a single class, passing the default values in __init__ is fine: class Base(object): def __init__(self, x=0, y=None): self.x = x self.y = y For inherited classes that need to override __init__ while keeping a
1
1361
by: Florian Paulus | last post by:
Hi group, i'm wondering how to assign an attribute to a field that a class inherited from a base class. Say base class has a field protected string message, so in the derived class i want to assign an attribute to it, i don't know how. i don't want to override the base class field, just add an attribute. and i can't add it in the base...
0
7894
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...
0
7821
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...
0
8172
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. ...
0
8320
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...
1
7929
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...
1
5697
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...
0
3814
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...
1
2328
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
1
1424
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.