Emulating C++ coding style

William Tanksley wtanksle at dolphin.openprojects.net
Thu Apr 22 19:15:11 EDT 1999


On Fri, 23 Apr 1999 06:08:07 +0900, Thooney Millennier wrote:
>Hello Everyone!

Hi!

>I usually use C++ ,so I want to make programs like
>I do using C++.

Bad idea.  How many other languages do you know?  If you only know C++,
you're now privledged to learn a second language.  Part of that is
learning that Good Ideas in one language are Bad Ideas in another.

>I don't figure out how to implement the followings
>by Python.

Okay...

>If you know any solutions,Please Help!

>1. #define statements
>  e.g. #define __PYTHON_INCLUDED__ 

Meaningless in Python.  A bad idea in C++, except for #include control
(which isn't needed in Python).

>       #define PYPROC(ARG) printf("%s",ARG)

A very bad idea in C++ -- you're supposed to use inline templatized
functions.  In Python, just define a function:

def PYPROC(ARG):  sys.stdout.write(ARG)

>2. stream class
>  e.g. cout << "hello python."<<endl;

VERY bad idea.  Bad even in C++.

sys.stdout.write("hello python." + "\n");

>3. const variables
>  e.g. const int NOCHAGE=1;

Mediocre idea in C++.  Not possible in Python, because in Python variables
aren't supposed to be typed in any way -- instead, they hold things which
are typed.

Why is it only a mediocre idea in C++?  Because a constant is part of an
interface, and a free constant is as bad as a free function; it pollutes
the global namespace.

In proper C++, your const will be contained inside a class (probably
static) to keep it out of the global namespace.  In proper Python, your
const will also be contained inside a class -- and __setattr__ will be
redefined to disallow changing any values.

class __myConsts:
  NOCHAGE = 1
  SOMECHAGE = 2
  
  # now make sure nobody can hack my values...
  def __setattrs__(self,attrname,value):
    raise "can't modify my constants!"

consts = __myConsts()

Now, after you import this module, you can access all your constants
through expressions such as consts.NOCHAGE, but you can't change them.

Well, not quite.  It turns out that you CAN change them, but only like
this:

__myConsts.NOCHAGE = 2

...and that only works from within the same file (because names beginning
with underscores are private), so it's probably what you wanted anyhow
(more like Java's 'final' keyword).

>4. access to class's members using "::"
>  e.g. some_class::static_value
>  e.g. some_class::static_func(x)

In Python, "." works for ALL object access.  Pointers, class variables,
and so on don't matter.

To be fair, I think this isn't a bad part of C++; :: notation makes some
things more clear.  But Python isn't C++.

>Thanks for reading.

Good luck.

>Thooney Millennier.

-- 
-William "Billy" Tanksley
"But you shall not escape my iambics."
           -- Gaius Valerius Catullus




More information about the Python-list mailing list