473,763 Members | 1,882 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dumb q: repeated inheritance in python?

Hi, here's a silly question. I'm wrote some code a while back that
looks like this:

import types

class Named(object):
def __init__(self,n m=''):
self.iname = ''
self.setnm(nm)
def setnm (self,nm):
if isinstance(nm, types.StringTyp e):
self.iname = nm
else:
raise TypeError, "Name passed to Named isn't a string."
def getnm (self):
return self.iname
name = property(getnm, setnm)

Pretty basic, a name attribute with simple type checking, it works
fine and the code using it is fine. Well, it was, until I came up
with an object that needed two names, with the same basic type
checking. Now the simplistic way to do that would be copy this class
to another class, say Named2, rename the property name2 and be done
with it. On the other hand, having code that's basically an exact
duplicate of other code except for some name changes seems a tad
inelegant. What I'd really like to do is inherit this same object
twice, but the second time rename the objects so that I get 'name2'
instead of 'name'. (And somehow rename the functions, and so on.)

But I can't figure out how to do it. Is there some way to do this? I
suspect there might be some way to do it with metaclasses, but I
haven't really wrapped my head around that stuff yet. Maybe something
with the new 'super' keyword? Beats me. Anyway, any help would be
great, thanks!!!
Jul 18 '05 #1
3 1502

"Corey Coughlin" <co************ @attbi.com> wrote in message
news:a8******** *************** ***@posting.goo gle.com...
Hi, here's a silly question. I'm wrote some code a while back that
looks like this:

import types

class Named(object):
def __init__(self,n m=''):
self.iname = ''
self.setnm(nm)
def setnm (self,nm):
if isinstance(nm, types.StringTyp e):
self.iname = nm
else:
raise TypeError, "Name passed to Named isn't a string."
def getnm (self):
return self.iname
name = property(getnm, setnm)

Pretty basic, a name attribute with simple type checking, it works
fine and the code using it is fine. Well, it was, until I came up
with an object that needed two names, with the same basic type
checking. Now the simplistic way to do that would be copy this class
to another class, say Named2, rename the property name2 and be done
with it. On the other hand, having code that's basically an exact
duplicate of other code except for some name changes seems a tad
inelegant. What I'd really like to do is inherit this same object
twice, but the second time rename the objects so that I get 'name2'
instead of 'name'. (And somehow rename the functions, and so on.)

But I can't figure out how to do it. Is there some way to do this? I
suspect there might be some way to do it with metaclasses, but I
haven't really wrapped my head around that stuff yet. Maybe something
with the new 'super' keyword? Beats me. Anyway, any help would be
great, thanks!!!


Why do the two names have to be in the same object instance? I'd
think the simplest approach would be to bind two instances of your
Named class to two different identifiers.

Otherwise, if you actually need some kind of a collection class, I'd
purpose build one: NamedCollection , or some such.

John Roth
Jul 18 '05 #2
co************@ attbi.com (Corey Coughlin) wrote in
news:a8******** *************** ***@posting.goo gle.com:
What I'd really like to do is inherit this same object
twice, but the second time rename the objects so that I get 'name2'
instead of 'name'. (And somehow rename the functions, and so on.)


I'm not sure if I exactly understood what you want, but does this help?
I think you are asking for two properties that access differently named
attributes but perform the same type checking in each case.

That sounds to me like you want a specialised property which can be done by
subclassing it:

---- begin test.py ----
class Name(property):
def __init__(cls, attrname):

def setnm(self, nm):
if isinstance(nm, str):
setattr(self, attrname, nm)
else:
raise TypeError("Name passed to %s isn't a string" %
self.__class__. __name__)

def getnm(self):
return getattr(self, attrname)

property.__init __(cls, getnm, setnm)
class TwoNamed(object ):
def __init__(self, iname='', jname=''):
self.iname, self.jname = iname, jname

name = Name('iname')
name2 = Name('jname')

x = TwoNamed('ivalu e', 'jvalue')
print "name, name2 =",x.name, x.name2

x.name = 'www'
x.name2 = 'xxx'

print "name, name2 =",x.name, x.name2
print "iname, jname =",x.iname, x.jname

x.name = 42 # Blows up
print x.name # Never reached.
----- end of test.py ----
--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #3
Thanks Duncan, that's exactly what I needed! I'm not very familiar
with subclassing properties, I guess I'll play around with it and see
if I can figure it out. But thanks again, it's great code!

------ Corey
Duncan Booth <du****@NOSPAMr cp.co.uk> wrote in message news:<Xn******* *************** *****@127.0.0.1 >...
co************@ attbi.com (Corey Coughlin) wrote in
news:a8******** *************** ***@posting.goo gle.com:
What I'd really like to do is inherit this same object
twice, but the second time rename the objects so that I get 'name2'
instead of 'name'. (And somehow rename the functions, and so on.)


I'm not sure if I exactly understood what you want, but does this help?
I think you are asking for two properties that access differently named
attributes but perform the same type checking in each case.

That sounds to me like you want a specialised property which can be done by
subclassing it:

---- begin test.py ----
class Name(property):
def __init__(cls, attrname):

def setnm(self, nm):
if isinstance(nm, str):
setattr(self, attrname, nm)
else:
raise TypeError("Name passed to %s isn't a string" %
self.__class__. __name__)

def getnm(self):
return getattr(self, attrname)

property.__init __(cls, getnm, setnm)
class TwoNamed(object ):
def __init__(self, iname='', jname=''):
self.iname, self.jname = iname, jname

name = Name('iname')
name2 = Name('jname')

x = TwoNamed('ivalu e', 'jvalue')
print "name, name2 =",x.name, x.name2

x.name = 'www'
x.name2 = 'xxx'

print "name, name2 =",x.name, x.name2
print "iname, jname =",x.iname, x.jname

x.name = 42 # Blows up
print x.name # Never reached.
----- end of test.py ----

Jul 18 '05 #4

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

Similar topics

7
3292
by: Hung Jung Lu | last post by:
Hi, I think Microsoft did look into Python when they designed C#. (E.g. they got rid of checked exceptions of Java.) However, they followed Java in avoiding multiple inheritance (MI), which is a great leap backward from C++, in my opinion. I understand the why of avoiding virtual data members, since performance is an issue. I understand the problems of MI in C++. But the cure (using interfaces) seems worse than the disease itself. Now...
4
1466
by: Dan Bullok | last post by:
I have a couple of classes: class Base: ... class Sub(Base): ... I want to subclass Base and Sub, i.e. define classes: class MyBase(Base):
6
3195
by: Brian Jones | last post by:
I'm sure the solution may be obvious, but this problem is driving me mad. The following is my code: class a(object): mastervar = def __init__(self): print 'called a'
2
4379
by: AIM | last post by:
Error in msvc in building inheritance.obj to build hello.pyd Hello, I am trying to build the boost 1.31.0 sample extension hello.cpp. I can not compile the file inheritance.cpp because the two files containing some templates: adjacency_list.hpp and mem_fn.hpp can not compile. Does anyone have any solutions?
13
3292
by: John Perks and Sarah Mount | last post by:
Trying to create the "lopsided diamond" inheritance below: >>> class B(object):pass >>> class D1(B):pass >>> class D2(D1):pass >>> class D(D1, D2):pass Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution
20
10084
by: km | last post by:
Hi all, In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? thanks in advance for enlightment ... here's the snippet #!/usr/bin/python
0
1194
by: Terry Hancock | last post by:
I've been discussing PyProtocols with a a friend collaborating with me on a SF game project, about the benefits and design concept of "component architecture", and I'm a little confused by what I'm learning. I learned the concepts of "component architecture" from the Zope project, where if I'm not mistaken, "components" are essentially python "mix-in" classes, and you make a class from components by using multiple inheritance and...
16
2943
by: devicerandom | last post by:
Hi, I am currently using the Cmd module for a mixed cli+gui application. I am starting to refactor my code and it would be highly desirable if many commands could be built as simple plugins. My idea was: - Load a list of plugin names (i.e. from the config file, or from the plugins directory) - Import all plugins found dynamically:
18
1689
by: GD | last post by:
Please remove ability to multiple inheritance in Python 3000. Multiple inheritance is bad for design, rarely used and contains many problems for usual users. Every program can be designed only with single inheritance. I also published this request at http://bugs.python.org/issue2667
10
4392
by: Aaron Gray | last post by:
Wikipedia says Python has Multiple Inheritance, is this true ? http://en.wikipedia.org/wiki/Multiple_inheritance Thanks, Aaron
0
9566
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
10149
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
10003
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
9943
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
8825
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
7370
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...
0
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3529
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2797
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.