473,544 Members | 1,928 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

can i implement virtual functions in python ?

Hi,

I'm new to python, so excuse me if i'm asking something dumb.
Does python provide a mechanism to implement virtual functions?
Can you please give a code snippet also...:)
Thanx in advance
-Prabu.
Jul 18 '05 #1
15 19302
my friend python coder, tell me all function are virtual in python , so...

"Prabu" <pr****@hotmail .com> a écrit dans le message news:
e7************* *************@p osting.google.c om...
Hi,

I'm new to python, so excuse me if i'm asking something dumb.
Does python provide a mechanism to implement virtual functions?
Can you please give a code snippet also...:)
Thanx in advance
-Prabu.

Jul 18 '05 #2
Prabu wrote:
Hi,

I'm new to python, so excuse me if i'm asking something dumb.
Does python provide a mechanism to implement virtual functions? [...]


What do you mean with "virtual function"?

If you mean virtual methods in the C++ sense, all methods are "virtual"
in Python.

-- Gerhard

Jul 18 '05 #3
JCM
Prabu <pr****@hotmail .com> wrote:
....
I'm new to python, so excuse me if i'm asking something dumb.
Does python provide a mechanism to implement virtual functions?


Others have given good responses, but I'll jump in anyway.

Virtual functions (using C++ terminology) are something limited to
statically-typed languages. A virtual function call will be resolved
dynamically, based on the runtime type of the object. A non-virtual
call will be resolved at compile-time, based on the declared type of
the object. Since Python is dynamically typed, the only possibility
is for all methods to be "virtual".
Jul 18 '05 #4
Hello Prabu,
I'm new to python, so excuse me if i'm asking something dumb.
Does python provide a mechanism to implement virtual functions?
Can you please give a code snippet also...:)


http://www.python.org/doc/current/tu...00000000000000

Miki
Jul 18 '05 #5
I think you can do something like this.

class Virtual:
def myFunc(self, x):
pass

class Implement(Virtu al):
def myFunc(self, x):
return x * x
Jul 18 '05 #6
pr****@hotmail. com (Prabu) wrote in message news:<e7******* *************** ****@posting.go ogle.com>...
Hi,

I'm new to python, so excuse me if i'm asking something dumb.
Does python provide a mechanism to implement virtual functions?
Can you please give a code snippet also...:)
Thanx in advance
-Prabu.


As others have mentioned, all methods are overridable in python. But
if you want to create a genuine Abstract Base Class, raise
NotImplementedE rrors for the virual methods. People will tell you
that this is not 'pythonic' (you should be using hasattr() to test for
interfaces) but I still find it useful from time to time.

PythonWin 2.3.2c1 (#48, Sep 30 2003, 09:28:31) [MSC v.1200 32 bit
(Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mh******@skipp inet.com.au)
- see 'Help/About PythonWin' for further copyright information.
class virtualClass: .... def __init__(self):
.... pass
.... def virtualMethod1( self):
.... raise NotImplementedE rror("virtualMe thod1 is virutal and
must be overridden.")
.... def concreteMethod1 (self):
.... print "The concrete method is implemented"
....
x = virtualClass() x.concreteMetho d1() The concrete method is implemented
x.virtualMethod 1() Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 5, in virtualMethod1
NotImplementedE rror: virtualMethod1 is virutal and must be overridden.
class subClass(virtua lClass): .... def virtualMethod1( self):
.... print "sub class implemented virtualMethod1"
....
y = subClass() y.concreteMetho d1() The concrete method is implemented
y.virtualMethod 1() sub class implemented virtualMethod1

Jul 18 '05 #7
logistix at cathoderaymissi on.net:
if you want to create a genuine Abstract Base Class, raise
NotImplementedE rrors for the virual methods. People will tell you
that this is not 'pythonic' (you should be using hasattr() to test for
interfaces) but I still find it useful from time to time.


Really? I find hasattr to be non-Pythonic. Just get the object, like

try:
method = obj.function_na me
except AttributeError:
... not implemented ...

However, I do use NotImplementedE rror so the exception
which percolates up is more obvious than AttributeError. It also
allows me to put in a docstring describing the interface requirements
of derived classes.

I also don't like the double attribute lookup in

if not hasattr(obj, "function_name" ):
... not implemented ...
else:
obj.function_na me(...)

but that's more a personal issue than Pythonic vs. non-Pythonic.

Andrew
da***@dalkescie ntific.com

Jul 18 '05 #8
Andrew Dalke wrote:

I also don't like the double attribute lookup in

if not hasattr(obj, "function_name" ):
... not implemented ...
else:
obj.function_na me(...)


Have you considered using getattr() with a default?

class Test:
def there(self):
print "there"

def default():
print "default"

t = Test()
for name in "there notThere".split ():
getattr(t, name, default)()
Peter
Jul 18 '05 #9
Peter Otten:
Have you considered using getattr() with a default?


Yes, I have. It isn't always the right solution, unless
you do a bit of trickery.

Consider

class Test:
def there(self):
return DBConnect("exam ple.com", "user", "passwd")

class TestNotThere:
pass

if random.choice([0, 1]) == 1:
x = Test()
else:
x = TestNotThere()

if hasattr(x, "there"):
conn = x.there()
conn.query("thi s where that is the other").dump()
print "There you go", conn.username
conn.shutdown()

You can't replace the hasattr(x, "there") with a
getattr(x, "there", default_functio n) because even if
the default function returned an object which implements
'query', 'shutdown' and 'user' correctly, the output will
contain the text "There you go", which shouldn't happen.

A better option getattr solution is to compare the
returned object against the default

f = getattr(x, "there", None)
if f is not None:
conn = f()
...

(Note that you must use 'is' here and not == because
the latter can trigger arbitrary Python code, which has
a different behaviour than the hasattr approach.)

However, suppose TestNotThere.th ere is not a method
but is the None object. The original hasattr code raises
a 'TypeError - not callable' exception but this getattr
version won't, which means the API is different and
allows errors to slip silently by.

The better solution is to create an object which you
can guarantee is not present anywhere else. For
example, you could do

class _default: pass # guaranteed to be unique

f = getattr(x, "there", _default)
if f is not _default:
conn = f()
...

I don't consider that code all that clean. It isn't obvious
why the _default class is needed. Compare that to my
prefered code

try:
f = x.there
except AttributeError:
pass
else:
conn = f()

This code is longer, and I admit it isn't the clearest (I
would prefer the exception case be after the else case).
It's also slower because of the exception creation, unless
exceptions are rare. But it exactly equivalent to the
hasattr test except without the double attribute lookup,
and it uses a standard construct instead of depending
on a class creation to make an object which is guaranteed
to be unique.

In any case, remember that I said it's a personal preference,

Plus, most of the time a getattr with a default value is
the right solution. It's just not a general panacea.

Andrew
da***@dalkescie ntific.com
Jul 18 '05 #10

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

Similar topics

4
1747
by: The Stevemeister | last post by:
Hi, I have an entity class (from a rendering engine) with about 100 functions now that are virtual. So far no slowdowns, but since I've done alot of work with OWL and MFC over the years, and I know that when the virtual functions get too many, OWL and MFC result to dispatch tables. Question is, at what point do I say, "At what point do I...
20
2379
by: Nemanja Trifunovic | last post by:
Something I don't get it: Say we have: ref class Base { virtual void SomeVirtualFunction() {Console::WriteLine(L"Base");} public: void SomeAccessibleFunction() {SomeVirtualFunction();}
17
3217
by: Riaan | last post by:
Hi Everybody, I created an abstract class containing all my pure virtual functions. I derived a new class from this and implemented all the functions needed. Every time I compile, I get the error : ..\file.cpp(189) : error C2259: 'FileInterface' : cannot instantiate abstract class due to following members: .\../../boffice/plugins.h(39) :...
12
4959
by: sojin | last post by:
Hi all, I'm a new to c++... and I've some doubts on "virtual" topics. 1) Can abstract base class have V-table? Here's the way,, Class CTemp{
2
2441
by: david.sanderson | last post by:
Hi, Hopefully this is thecorrect group, its a bit C++ and a bit POSIX... Ive had a look in the archives, and Im a bit confused.... I have some classes in a shared library (a .so on a QNX system) which I want to instantiate into shared memory so that 2 processes can both operate on the same data. The classes have a quite derived...
5
1984
by: Dilip | last post by:
In a polymorphic hierarchy is it common practice to have public virtual functions in the base class with a default empty implementation and let the derived classes decide whether they want to override it or not? In such cases what would be the access levels of those functions in both base and derived classes? struct AbstractBase {...
7
1763
by: v4vijayakumar | last post by:
Is it possible to implement member object's virtual functions, in the containing class? If not, is it possible to simulate this behavior? ex: class test { protected: virtual void fun() = 0; };
6
2048
by: Pallav singh | last post by:
Hi All How Does compiler implement virtual destructor ??? as we all know if base class destructor is virtual..........then while wriiting statemnt like this Base * b = new Derived( ); delete b;
6
3210
by: Vijay Meena | last post by:
Hi, Private functions can be virtual in C++ ( unlike Java) ? What is the use of private virtual functions ? Below is the code - #include <iostream> class Foo { public: virtual void test() { std::cout << "Foo::test()" << std::endl; } };
0
7373
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...
0
7625
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. ...
0
7781
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...
1
7389
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
5928
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...
1
5306
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...
1
1848
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
993
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
677
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.