473,569 Members | 2,704 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strategy pattern and non-public virtual functions

Hi python experts

In C++ I can do something like this:
class Base {
public:
void f() { this->f_(); }
private:
virtual void f_() = 0;
};

class Derived : public Base {
private:
void f_() { // Do something }
};

int main() {
Derived d;
d.f();
}

The point of this is that the a number of classes will inherit from
Base and only implement a private member function that only will be
accessed from the base class public 'f' function.
The Base::f() can then perform validation of input/return values, add
logging and things like that.
The users of the derived classes are unable to bypass this base class
function.

I've been wanting to do the same thing in python, to make sure that
there is no confusion about what function to call.

Just translating this code to python won't work, due to the name
mangling of private functions:
class B(object):
def f(self):
self.__f()

class D(B):
def __f(self):
pass

d = D()
d.f()

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in f
AttributeError: 'D' object has no attribute '_B__f'

So my questions are:
1. Is there a "pythonic" way to do what I'm trying to do?
2. Should I be doing this at all? Any thoughts?

Jun 5 '06 #1
5 2060
wrote:
The users of the derived classes are unable to bypass this base class
function.


Just to be clear, the users of the derived C++ classes *are* able to bypass
the base class function and call f_() directly, they just have to be
prepared to twist the rules somewhat. I know: I've been in the situation
where there was absolutely no other way to get the job done other than to
call a private method in a class supplied in a library which I couldn't
change.

To do the same in Python you simply make a rule 'dont call f_ directly' and
you get effectively the same thing: users can call f_ if they really want,
but they are breaking the rules if they do. The difference in Python is
that you don't have to go to such extremes to break the rules.

The Pythonic way to do it:

class B(object):
def f(self):
self._f()

class D(B):
def _f(self):
pass

d = D()
d.f()

Calling a method with a single leading underscore from outside the
implementation of the class is generally accepted in Python to be 'breaking
the rules' and therefore something only to be done by consenting adults in
the full knowledge of the consquences of their actions.
Jun 5 '06 #2
py***********@g mail.com wrote:
Just translating this code to python won't work, due to the name
mangling of private functions:
class B(object):
def f(self):
self.__f()

class D(B):
def __f(self):
pass

d = D()
d.f()

So my questions are:
1. Is there a "pythonic" way to do what I'm trying to do?
Just use a single underscore, i.e. "_f" instead of "__f".

2. Should I be doing this at all? Any thoughts?


I can't spot the strategy pattern here; neither in the C++ code
nor in the Python code. For this to be the strategy pattern,
you should have two objects: the context, and the strategy
object. So for example, you could have

class Context:
def f(self):
return self.strategy.f ()

class D:
def f(self):
pass

Then, assigning to context.strateg y lets you change the
strategy dynamically.

It's not clear to what you are trying achieve with your
pattern, so it is hard to tell whether you should do this
at all. Most likely, the answer is "no".

If you are really looking for the strategy pattern:
be aware that people often use the strategy pattern
as a work-around for functions not being first-class
objects. In Python, they are, so you can often allow
for arbitrary callables in the strategy pattern.

Regards,
Martin
Jun 5 '06 #3
Le Lundi 05 Juin 2006 16:07, py***********@g mail.com a écrit*:
class Base {
* public:
* * void f() { this->f_(); }
* private:
* * virtual void f_() = 0;
};

class Derived : public Base {
* private:
* * void f_() { // Do something }
};

int main() {
* * Derived d;
* * d.f();
}


This is just polymorphism, not strategy pattern, and I would expect f_ to be
protected here not private.

You want to ensure derived class will use a given method in the Base class,
this could be done explicit with a good naming convention as Duncan said, but
here is a strategy pattern to ensure a sanity check for example :

class strategyBase(ob ject) :
def __call__(self, *sa) : raise NotImplementedE rror('abstract class')

class InputProcessor( object) :

def sanitize(self, *a) :
return a

def f(self, *a) :
sa = self.sanitize(* a)
return self.strategy(* sa)

def __setStrategy(s elf, strat) :
if not isinstance(stra t, strategyBase) :
raise ValueError("str at must be of type strategyBase")
self.__strat = strat

strategy = property(fget=l ambda s : s.__strat, fset=__setStrat egy)

The main purpose of this is to define a common API for all Strategies, and
this is really useful if you intend to manage many of them.

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 5 '06 #4
py***********@g mail.com writes:
Hi python experts

In C++ I can do something like this:
class Base {
public:
void f() { this->f_(); }
private:
virtual void f_() = 0;
};

class Derived : public Base {
private:
void f_() { // Do something }
};

int main() {
Derived d;
d.f();
}

[...]

The others have already answered the Python question and pointed out
this isn't really the Strategy Pattern.

Still, these slides from Alex Martelli specifically on the Template
Method DP in Python are probably very relevant to you:

http://www.aleax.it/Python/os03_template_dp.pdf
John
Jun 5 '06 #5
py***********@g mail.com a écrit :
Hi python experts

In C++ I can do something like this:
class Base {
public:
void f() { this->f_(); }
private:
virtual void f_() = 0;
};

class Derived : public Base {
private:
void f_() { // Do something }
};

int main() {
Derived d;
d.f();
}
<ot>
This is eventually the template method pattern, but certainly not the
strategy pattern.
</ot>

The point of this is that the a number of classes will inherit from
Base and only implement a private member function that only will be
accessed from the base class public 'f' function.
The Base::f() can then perform validation of input/return values, add
logging and things like that.
This is usually done in Python with function decorators. But the
implementer of the derived class

(snip - cf other posts in this thread)
So my questions are:
1. Is there a "pythonic" way to do what I'm trying to do?

2. Should I be doing this at all? Any thoughts?


Doing what ? adding logging, validation etc, or using the template
method pattern ?-)
Jun 5 '06 #6

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

Similar topics

8
6971
by: gsv2com | last post by:
One of my weaknesses has always been pattern matching. Something I definitely need to study up on and maybe you guys can give me a pointer here. I'm looking to remove all of this code and just use pattern matching to determine if the proper amount of numeric characters has been met. Here is the function I've already done. Any help you can...
5
1917
by: Ben Jeurissen | last post by:
Hello, I have to deal with the following issue in C++: Two threads are started from the main thread, both capturing images from a different firewire camera. Both threads take shots of 460800 bytes at a rate of 30 frames per second. This works fine, without frame loss, and I can display the two framestreams on screen. Now I would like...
21
2436
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought maybe a Template can be use for that, but C# does not support Templates (will be C# generics in mid 2005). Does anyone have a solution on how the...
7
2726
by: Jeff | last post by:
I plan to write a Windows Forms MDI application for a medical office. Users must be able to select a patient and view related information on multiple forms; with1-4 forms opened at the same time for the same patient; each form showing a different type of patient-related information. After viewing information for one patient (say on 3 forms...
6
4693
by: Daniel Santa Cruz | last post by:
Hello all, I've been trying to go over my OO Patterns book, and I decided to try to implement them in Python this time around. I figured this would help me learn the language better. Well, I've gotten stuck with my first go at OO patterns with Python. I guess it goes without say that some of the stuff that are taken for granted in most...
0
1352
by: ltruett | last post by:
I'm almost done my series of design patterns using PHP 5. Today's pattern is the Strategy Pattern. http://www.fluffycat.com/PHP-Design-Patterns/Strategy/ In the Stratedy Pattern a "family of algorythms" is used interchangably by calling clients. This is the second pattern in as many days as I've used my older work with patterns in...
1
2484
by: Nick | last post by:
Hi, I read somewhere recently that the strategy pattern could be used instead of using switch command on an enum (for example). How would this work? A small example would be great. Thanks, Nick
8
2146
by: CK | last post by:
Good Morning All, I am writing an app to calculate the cost of a hotel room. I am new to c++. I have decided to try using the Strategy Design Pattern. I want a superclass HotelRoom, and then make 3 classes that inherit from it. SuiteRoom, StandardRoom, and DeluxeRoom. The price of the room is based on 3 factors, if there is are more then 2...
3
1468
by: Mike TI | last post by:
Aug 2, 2007 12:00pm Hi all I have to design and program an application which will be used in three countries. It would be a fairly large application with lot of data entry. The database hence has to be consolidated and at one location. Now the internet is excellent in one country and reasonable in the other
8
2753
by: Slaunger | last post by:
Hi all, I am a Python novice, and I have run into a problem in a project I am working on, which boils down to identifying the patterns in a sequence of integers, for example ..... 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6 1 6 6 1 6 6 1 6 6 1 6 6...
0
7698
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...
1
7673
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...
0
7970
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...
0
6284
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...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
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
2113
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
1213
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
937
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...

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.