473,405 Members | 2,349 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,405 software developers and data experts.

Inheritance question

Hello,

Say I have a base class called "A"

class A:
_value
__init__(self, value):
self._value = value

and two derived classes "B1" and "B2":

class B1(A):
def doPrint(self):
print "B1: " + str(self._value)

class B2(A):
def doPrint(self):
print "B2: " + str(self._value)
is there a way that I could change my class A to something like:

class A:
_value
__init__(self, value):
self._value = value
if value > 10:
set myself as an instance of B1 # How can I do that?
else:
set myself as an instance of B2

in the real situation "value" is encoded and the way to know what kind of A
it is, is more complex than just look at the value.

Thanks for your help and time.

Yannick
Jul 18 '05 #1
5 1415
Yannick Turgeon wrote:
is there a way that I could change my class A to something like:

class A:
_value
__init__(self, value):
self._value = value
if value > 10:
set myself as an instance of B1 # How can I do that?
else:
set myself as an instance of B2

in the real situation "value" is encoded and the way to know what kind of
A it is, is more complex than just look at the value.


[Requires newstyle classes]
class A(object): .... def __new__(cls, value):
.... if value > 10:
.... return super(cls, A).__new__(B1, value)
.... else:
.... return super(cls, A).__new__(B2, value)
.... def __init__(self, value):
.... self._value = value
.... class B1(A): .... def doPrint(self):
.... print "B1:", self._value
.... class B2(A): .... def doPrint(self):
.... print "B2:", self._value
.... A(1).doPrint() B2: 1 A(100).doPrint()

B1: 100

You can do it, but it's certainly bad design because A has to know all its
subclasses. If you go with the above I recommend that you use some kind of
registry instead of hardcoding the subclasses in A.__new__().

Peter

Jul 18 '05 #2
Yannick Turgeon <no****@nowhere.com> wrote:
class A:
_value
__init__(self, value):
self._value = value
if value > 10:
set myself as an instance of B1 # How can I do that?


self.__class__ = B1

Whether you WANT to do that is quite another issue: you most likely
don't, though you wrongly believe you do. Use a factory-function
pattern if you want to generate different possible classes, don't use
black magic such as changing an instance's class on the fly unless there
are _really good_ reasons (an example of a really good reason, IMHO, is
given by a recipe in the Cookbook that presents a bounded-ring-buffer
class... its instances commute from NotFull to Full classes once and for
all when they switch from non-full to full, NOT at instance generation
time...).
Alex
Jul 18 '05 #3
Hello,

Thanks to reply. My question has been answered but I'm now wondering if I do
this the best way.

In the real situation I'm implementing a protocol. "A" represent a command.
Say "0144AYHR78" (encoded data) means "Add client Joe" and "0589UAWERT"
means "Ship 3 compressors to Joe". What I want to do is to create a "A"
instance which find the command type and parameters and "mutate" itself to
the good command. All command parameters ("Joe" for the first one and
"3,compressor,Joe" for the secondeone) are kept in a sigle list.So B1 and B2
would define the function "getClient()" and B2 would define "getQty()" and
"getProduct()" and some other command-specific work.

while True:
encoded_data = readEncodedData()
command = A(encoded_data)
type_ = command .getType() # Define in "A"
if type_ == A.ADD:
# Do what I have to do with a "Add" command using the "command"
instance (B1)
elif type_ == A.SHIP:
# Do what I have to do with a "Ship" command using the "command"
instance (B2)
...

Any suggestion to do this in a better way

Yannick

You can do it, but it's certainly bad design because A has to know all its
subclasses. If you go with the above I recommend that you use some kind of
registry instead of hardcoding the subclasses in A.__new__().

Peter

Jul 18 '05 #4
Yannick Turgeon wrote:
Hello,

Thanks to reply. My question has been answered but I'm now wondering if I
do this the best way.

In the real situation I'm implementing a protocol. "A" represent a
command. Say "0144AYHR78" (encoded data) means "Add client Joe" and
"0589UAWERT" means "Ship 3 compressors to Joe". What I want to do is to
create a "A" instance which find the command type and parameters and
"mutate" itself to the good command. All command parameters ("Joe" for the
first one and "3,compressor,Joe" for the secondeone) are kept in a sigle
list.So B1 and B2 would define the function "getClient()" and B2 would
define "getQty()" and "getProduct()" and some other command-specific work.

while True:
encoded_data = readEncodedData()
command = A(encoded_data)
type_ = command .getType() # Define in "A"
if type_ == A.ADD:
# Do what I have to do with a "Add" command using the "command"
instance (B1)
elif type_ == A.SHIP:
# Do what I have to do with a "Ship" command using the "command"
instance (B2)
...

Any suggestion to do this in a better way


Here's how I would do it based on the above:

class Ship:
def __init__(self, args):
""" knows how to decode args """
self.quantity = # your code
self.item = # your code
self.client = # your code
def execute(self):
""" do what is necessary for shipment """

class Add:
def __init__(self, args):
""" knows how to decode args """
self.client = # your code
def execute(self):
""" add a client """

commands = {
"0144": Add, # assuming the first 4 chars encode the command
"0589": Ship,
}

def decode(data):
""" separate the command and its arguments,
hopefully possible without having to know
individual commands
"""
return data[:4], data[4:] # may actually be more complicated

while True:
type_, args = decode(readEncodedData())
cmd = commands[type_](args)
cmd.execute()

Ship and Add may or may not share a common base class depending on whether
you can factor out common functionality - e. g. a mixin that knows how
decode the client, but you do not need to artificially introduce a common
base class as a factory for the actual instances. Just make sure that
__init__() takes a single argument and an execute() method taking no
arguments is available.
The client code (the while loop) is independent of the actual command, so
ideally you just have to create a new class for a new command and enter it
into the commands dictionary.

Peter

Jul 18 '05 #5
Yannick Turgeon <no****@nowhere.com> wrote:
...
Say "0144AYHR78" (encoded data) means "Add client Joe" and "0589UAWERT"
means "Ship 3 compressors to Joe". What I want to do is to create a "A"
instance which find the command type and parameters and "mutate" itself to
the good command. All command parameters ("Joe" for the first one and ... Any suggestion to do this in a better way


Yeah -- Peter Otten explained in more detail, but summing up: what you
need is a Factory Design Pattern -- a function that takes the encoded
data, decodes it, instantiates the appropriate class (probably based on
a dict to map code->class) with the appropriate parameters. No reason
whatsoever to have an instance mutate its own class in this case.
Alex
Jul 18 '05 #6

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

Similar topics

1
by: KK | last post by:
Windows Forms Inheritance, Incomplete? I was playing around with Windows Forms and found out this Forms Inheritance feature. The moment I saw that, I felt this can be used effectively if the...
2
by: KK | last post by:
** Posting it here cause after couple of days no body responded.** I was playing around with Windows Forms and found out this Forms Inheritance feature. The moment I saw that, I felt this can...
4
by: Dave Theese | last post by:
Hello all, The example below demonstrates proper conformance to the C++ standard. However, I'm having a hard time getting my brain around which language rules make this proper... The error...
8
by: __PPS__ | last post by:
Hello everybody, today I had another quiz question "if class X is privately derived from base class Y what is the scope of the public, protected, private members of Y will be in class X" By...
22
by: Matthew Louden | last post by:
I want to know why C# doesnt support multiple inheritance? But why we can inherit multiple interfaces instead? I know this is the rule, but I dont understand why. Can anyone give me some concrete...
45
by: Ben Blank | last post by:
I'm writing a family of classes which all inherit most of their methods and code (including constructors) from a single base class. When attempting to instance one of the derived classes using...
6
by: VR | last post by:
Hi, I read about Master Pages in ASP.Net 2.0 and after implementing some WinForms Visual Inheritance I tryed it with WebForms (let's say .aspx pages, my MasterPage does not have a form tag itself...
5
by: Noah Roberts | last post by:
Is there anything that says that if you virtually inherit from one class you have to virtually inherit from anything you inherit from?
3
by: RSH | last post by:
I have a simple question regarding inheritance in a web form. I have a DropDownList in an aspx form. It is called DropDownList1 I have a class that will be overriding the render event so I...
8
by: RSH | last post by:
Hi, I am working on some general OOP constructs and I was wondering if I could get some guidance. I have an instance where I have a Base Abstract Class, and 4 Derived classes. I now need to...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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,...
0
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...
0
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...
0
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,...

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.