Python/C++ vs. Perl/C++

Classes

Here's a little exercise that should demonstrate that Python is a more natural scripting language option than Perl, especially for C++ programmers. This is but one of many possible examples.

The task: Create a simple class Person and show a basic use.

Comment on this topic

C++
class Person
{
  public:
    Person(int age);
    ~Person();

    int age() const;

  private:
    int _age;
};

Person::Person(int age)
{
  _age = age;
}

Person::~Person()
{
  cout << "destructor";
}

int Person::age() const
{
  return _age;
}

// Using the class...
Person p(25);
cout << p.age();

Admittedly an oversimplified class, just for illustration.

Perl
package Person;
use strict;

sub new
{
  my $class = shift;
  my $age = shift or die "Must pass age to new";

  my $rSelf = {'age' => $age};

  bless ($rSelf, $class);

  return $rSelf;
}

sub DESTROY
{
  print "destructor";
}

sub age
{
  my $rSelf = shift;

  return $rSelf->{'age'};
}

1;

# Using the class...
my $p = new Person(25);
print $p->age();

Some definite weirdness to the C++ programmer. Must check that the proper parameters are passed to new. Must create hash that holds data members, that is the "self" or "this" passed implicitly to every function. Must access data members using the hash syntax. Must return 1 from the module. Must call the magical "bless" function.

Python
class Person:
  def __init__(self, age):
    self._age = age

  def __del__(self):
    print 'destructor'

  def age(self):
    return self._age

# Using the class...
p = Person(25)
print p.age()

Quite C++ish.