473,659 Members | 3,420 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is it possible to have instance variables in subclasses of builtins?

I've recently used subclasses of the builtin str class to good effect.
However, I've been unable to do the following:

1) Call the constructor with a number of arguments other than
the number of arguments taken by the 'str' constructor.

2) Create and use instance variables (eg. 'self.x=1') in
the same way that I can in a 'normal' class.

As an example of what I mean, here's a short little session:
class a(str): .... def __init__(self, a, b):
.... str.__init__(a)
.... self.b = b
.... x = a("h", "g") Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)
(hmm, on reflection, I shouldn't have used 'a' as a
parameter to __init__--but that's merely bad
style, not the cause of the error :-) )

On the other hand, this example works:
class b(str): .... def __init__(self, x):
.... str.__init__(x)
.... x = b("h")
x 'h'


Is it possible to circumvent the above restrictions?

Thanks,
Ken
Jul 18 '05 #1
2 1335

The following might work for you:

from UserString import UserString
class b(UserString):
def __init__(self, x, y, z):
self.y=y
self.z=z
self.x=x
UserString.__in it__(self, x)
return
x=b('h', 1, 2)
x.z 2 x.y 1 x.x 'h' len(x)
1

Uses old UserString class.

HTH,
Larry Bates
Syscon, Inc.
"Kenneth McDonald" <ke************ ****@sbcglobal. net> wrote in message
news:sl******** *************** ********@g4.gat eway.2wire.net. ..
I've recently used subclasses of the builtin str class to good effect.
However, I've been unable to do the following:

1) Call the constructor with a number of arguments other than
the number of arguments taken by the 'str' constructor.

2) Create and use instance variables (eg. 'self.x=1') in
the same way that I can in a 'normal' class.

As an example of what I mean, here's a short little session:
class a(str): ... def __init__(self, a, b):
... str.__init__(a)
... self.b = b
... x = a("h", "g") Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)
(hmm, on reflection, I shouldn't have used 'a' as a
parameter to __init__--but that's merely bad
style, not the cause of the error :-) )

On the other hand, this example works:
class b(str): ... def __init__(self, x):
... str.__init__(x)
... x = b("h")
x 'h'


Is it possible to circumvent the above restrictions?

Thanks,
Ken

Jul 18 '05 #2
"Kenneth McDonald" <ke************ ****@sbcglobal. net> wrote in message
news:sl******** *************** ********@g4.gat eway.2wire.net. ..
I've recently used subclasses of the builtin str class to good effect.
However, I've been unable to do the following:

1) Call the constructor with a number of arguments other than
the number of arguments taken by the 'str' constructor.

2) Create and use instance variables (eg. 'self.x=1') in
the same way that I can in a 'normal' class.

As an example of what I mean, here's a short little session:
class a(str): ... def __init__(self, a, b):
... str.__init__(a)
... self.b = b
... x = a("h", "g") Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)
The problem is that "str" is an immutable type. Therefore, to change the
constructor, you need to override the __new__ method. See
http://www.python.org/2.2.1/descrintro.html#__new__

Here's an example:
class two(str): def __new__(cls, a, b):
return str.__new__(cls , a)
def __init__(self, a, b):
self.b = b
z = two("g", "h")
z 'g' z.b

'h'

Note that both arguments (a and b) get passed to both the __new__ and
__init__ methods, and each one just ignores the one it doesn't need.
--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.
Jul 18 '05 #3

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

Similar topics

3
1755
by: Michael Hoffman | last post by:
I was compelled to write this today for some reason. builtins = """__import__ abs basestring bool callable chr classmethod cmp compile complex delattr dict dir divmod enumerate eval execfile file filter float frozenset getattr globals hasattr hash help hex id input int isinstance issubclass iter len list locals long map max min object oct open ord pow property range raw_input reduce
0
1856
by: Dave | last post by:
Hi everyone, (I already posted this to the VS.NET IDE news group without any responses, so I'm attempting one more time in this group) The issue I'm having is occuring in the IDE of VS.NET 2003, although I'm not sure what is actually causing the problem. I can't summarize the issue, so please read on to find out more. I've created a BaseDialogEditor class that allows a developer (namely me) to create Modal editors for controls at...
0
911
by: Dave | last post by:
Hi everyone, (I already posted this to the VS.NET IDE news group without any responses, so I'm attempting one more time in this group) The issue I'm having is occuring in the IDE of VS.NET 2003, although I'm not sure what is actually causing the problem. I can't summarize the issue, so please read on to find out more. I've created a BaseDialogEditor class that allows a developer (namely me) to create Modal editors for controls at...
10
2307
by: steve bull | last post by:
I have a class SwatchPanel which takes Swatch as a parameter type. How can I call a static function within the Swatch class? For example the code below fails on TSwatch.Exists. How can I get the call to work? Exists is a method within the Swatch class NOT the SwatchPanel class. Is this possible? Suggestions would be very welcome.
0
8337
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
8851
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
8628
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
7359
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
6181
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
4175
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...
1
2754
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
2
1978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
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.