15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

572<br />

Using Objects<br />

Creating a Python dictionary<br />

A dictionary contains values and keys assigned to each value. To create, use<br />

curly brackets like this:<br />

dictionaryname = {key1:value1, key2:value2, key3:value3}<br />

To retrieve a value using its key, use the get command like this:<br />

Variable = dictionary.name.get(key)<br />

Using Objects<br />

Both Perl and Python are true object-oriented <strong>programming</strong> languages<br />

(unlike C++), so you have no choice but to create and use objects in your<br />

programs. To create an object, you must define a class. In Perl, a typical<br />

class definition looks like this:<br />

package className;<br />

sub new {<br />

my $objectname = {<br />

Data;<br />

Data;<br />

};<br />

bless $objectname, $className;<br />

return $objectname;<br />

sub methodname{<br />

Commands;<br />

Commands;<br />

};<br />

In Python, a class looks like this:<br />

class ClassName:<br />

Data<br />

Data<br />

def methodname (self):<br />

Commands<br />

Commands<br />

Commands<br />

A class lists properties (data) along with one or more methods, which contain<br />

code <strong>for</strong> manipulating an object in some way.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!