473,385 Members | 1,712 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

creating an object from base class

i wish to have some extended functionality added to sockets

i can create my own socket class class mysocket(socket.socket):

and all should be fine. Except, the sockets are created for me by the
accept method, listening on port. So how can i take the standard
socket created for me and create a 'mysocket'. I need a method that
will initialise any new properties i have added in my class, but how
can i change the class of the socket created?

Apr 27 '07 #1
3 1479
io*****@attglobal.net a écrit :
i wish to have some extended functionality added to sockets

i can create my own socket class class mysocket(socket.socket):

and all should be fine. Except, the sockets are created for me by the
accept method, listening on port. So how can i take the standard
socket created for me and create a 'mysocket'. I need a method that
will initialise any new properties i have added in my class, but how
can i change the class of the socket created?
object.__class__ = OtherClass

But this may not be the wisest solution. What you want is not
inheritance, it's decoration (AKA wrapping). IOW : instead of directly
using accept(), use a wrapper around it that will returns socket objects
wrapped in your own class.

My 2 cents...
Apr 27 '07 #2
Quote iogilvy:
i wish to have some extended functionality added to sockets

i can create my own socket class class mysocket(socket.socket):

and all should be fine. Except, the sockets are created for me by the
accept method, listening on port. So how can i take the standard
socket created for me and create a 'mysocket'. I need a method that
will initialise any new properties i have added in my class, but how
can i change the class of the socket created?
Someone correct me if I'm wrong, but I don't believe it's possible to
change the type of objects made from builtin classes. Though if it's a
custom class you can, for example:
>>class Foo: pass
class Bar: pass
obj = Foo()
obj.__class__ = Bar

One option is to make your custom socket a wrapper around
socket.socket and then pass through the calls you don't want to handle
to socket.socket. The downside to this is there are quite a lot of
methods that need to be accounted for. For example:
>>class CustomSocket:
def __init__(self, socket):
self.socket = socket
def connect(self, address):
self.socket.connect( address + '.some.tld' )
[etc]

...

s = server_socket.accept()
s = CustomSocket(s)

Another approach you might want to look at is populating your object
at runtime through a function. This won't give it the type you want,
but it will give it any methods and attributes it would have gotten
from your class with the added benefit of it still being of type
socket.socket. Example:
>>def modify_socket( socket ):
socket.cabbages = 'Yuk'
socket.apples = 'Yum'

def info():
print 'Cabbages? %s\nApples? %s' % (socket.cabbages, socket.apples)
obj.show_info = info

...

s = server_socket.accept()
modify_socket( s )
s.show_info()
Cabbages? Yuk
Apples? Yum
>>s.apples = 'Yummie'
s.show_info()
Cabbages? Yuk
Apples? Yummie
>>type(s)
<class 'socket._socketobject'>

Good luck.

Ian
Apr 27 '07 #3
Ian Clark wrote:
Quote iogilvy:
>i wish to have some extended functionality added to sockets

i can create my own socket class class mysocket(socket.socket):

and all should be fine. Except, the sockets are created for me by the
accept method, listening on port. So how can i take the standard
socket created for me and create a 'mysocket'. I need a method that
will initialise any new properties i have added in my class, but how
can i change the class of the socket created?

Someone correct me if I'm wrong, but I don't believe it's possible to
change the type of objects made from builtin classes. Though if it's a
custom class you can, for example:
>>>class Foo: pass
class Bar: pass
obj = Foo()
obj.__class__ = Bar

Yes, assuming you weren't asking a rhetorical question you will
eventually run up against
>>class myClass1(object): pass
...
>>class myClass2(object): pass
...
>>mc1 = myClass1()
type(mc1)
<class '__main__.myClass1'>
>>mc1.__class__ = myClass2
type(mc1)
<class '__main__.myClass2'>
>>2 . __class__ = myClass1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types
>>>
This doesn't qualify as error message of the year, but it clearly tells
you you aren't going to get around the prohibition. We also see
>>o = object
o.__class__ = myClass2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'object'
>>>
which gives a much better error message. Of course it'll probably only
take Alex Martelli a few minutes to find a workaround or counter-example.
One option is to make your custom socket a wrapper around
socket.socket and then pass through the calls you don't want to handle
to socket.socket. The downside to this is there are quite a lot of
methods that need to be accounted for. For example:
>>>class CustomSocket:
def __init__(self, socket):
self.socket = socket
def connect(self, address):
self.socket.connect( address + '.some.tld' )
[etc]

...

s = server_socket.accept()
s = CustomSocket(s)
This technique is formally called "delegation" if you want to Google it.
>
Another approach you might want to look at is populating your object
at runtime through a function. This won't give it the type you want,
but it will give it any methods and attributes it would have gotten
from your class with the added benefit of it still being of type
socket.socket. Example:
>>>def modify_socket( socket ):
socket.cabbages = 'Yuk'
socket.apples = 'Yum'

def info():
print 'Cabbages? %s\nApples? %s' % (socket.cabbages, socket.apples)
obj.show_info = info

...

s = server_socket.accept()
modify_socket( s )
s.show_info()
Cabbages? Yuk
Apples? Yum
>>>s.apples = 'Yummie'
s.show_info()
Cabbages? Yuk
Apples? Yummie
>>>type(s)
<class 'socket._socketobject'>
Of course that approach sucks if sockets happen to have an organes or
apples attribute that's used in the inner workings of the class. This is
when the C++ devotees start screaming about protected and private
variables. Just ignore them :-)

[Note: these remarks are more for the OP than Ian]

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get Python in your .sig and on the web. Blog and lens
holdenweb.blogspot.com squidoo.com/pythonology
tag items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------

Apr 28 '07 #4

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

Similar topics

21
by: Jason Heyes | last post by:
I want to allow objects of my class to be read from an input stream. I am having trouble with the implementation. Here are the different approaches I have tried: // Version 1.0 - Default...
2
by: Josh Mcfarlane | last post by:
I'm doing recomposition of objects from binary streams, and the best way for me to write them out is to write base class data first, forward to inherited classes, pointer class values, etc. Now,...
15
by: Carlos Lozano | last post by:
Hi, What is the right way to create an OCX COM component. The component is already registerred, but can't create an instance. I am using the reference to the interop module created. If I use...
8
by: Stephen Adam | last post by:
Hi there, I am developing a web site with a number of pages, I want each page to have the same heading section which will include both the raw html and vb.net code which handle rollovers for...
17
by: Lee Harr | last post by:
I understand how to create a property like this: class RC(object): def _set_pwm(self, v): self._pwm01 = v % 256 def _get_pwm(self): return self._pwm01 pwm01 = property(_get_pwm, _set_pwm)
3
by: Simon Hart | last post by:
Hi, I am trying to implement some functionality as seen in MS CRM 3.0 whereby a basic Xml is deserialized into an object which contains properties. What I want to do from here is; cast the basic...
10
by: benliu | last post by:
Is there an easy/special way to turn a base object into a derived object? So for example, given the following: class MyString : String { .... }
26
by: nyathancha | last post by:
Hi, How Do I create an instance of a derived class from an instance of a base class, essentially wrapping up an existing base class with some additional functionality. The reason I need this is...
3
by: Bartholomew Simpson | last post by:
I am writing some C++ wrappers around some legacy C ones - more specifically, I am providing ctors, dtors and assignment operators for the C structs. I have a ton of existing C code that uses...
1
by: Charles Law | last post by:
I have a base class MyBaseClass, and several classes that inherit from it: MyClass1, MyClass2, etc. The base class implements IEnumerable(Of IMyBaseClassRow). The base class has a DataTable...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...

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.