Make App Pie

Training for Developers and Artists

from Apple to Raspberry Pi: Making Classes in Python

appleberryObjective-C and Python are similar when it comes to defining new classes, but be careful with their differences. In Objective-C we would define a class with two files: a header and an implementation file. In the header we would declare properties like this

@interface PDPythonStuff : NSObject
     @property int a;
     @property int b;
@end

And possibly public methods

@interface PDPythonStuff : NSObject

     @property int a;
     @property int b;

     +(int)myFunction:(int)a b:(int)b;
     -(int)montyFunction:(int)a b:(int)b;
     -(int)montyFunction;
@end

In the implementation file we would have the code for the methods

@implementation PDPythonStuff

+(int)myFunction:(int)a b:(int)b{
    return a+b*b;
}

-(int)montyFunction:(int)a b:(int)b{
    return a+b*b;
}
-(int)montyFunction{
    return self.a+self.b*self.b;
}

@end

Finally we import the class into another class we are working with, such as a ViewController subclass

#import "PDMontyPython.h"

We would set up a property of the subclass for our instance

@interface PDViewController ()

    @property PDPythonStuff *montyPython;

@end

Allocate space and initialize the instance

    PDPythonStuff *montyPython = [[PDPythonStuff alloc]init];

We are now free to use it. A very simple example would be this which executes with the press of a button:

@implementation PDViewController{

}
- (IBAction)myButtonPressed:(UIButton *)sender {
    //calling the class method
    NSLog(@"myFunction PDPythonStuff = %i",[PDPythonStuff myFunction:5 b:25]);

    //initialize an instance
    PDPythonStuff *montyPython = [[PDPythonStuff alloc]init];
    //the method with parameters
    NSLog(@"myFunction montyPython = %i",[montyPython montyFunction:5 b:25]);

    //set the properties
    montyPython.a=5;
    montyPython.b=25;

    //the method using properties
    NSLog(@"myFunction montyFunction = %i",[montyPython montyFunction]);

}

@end

Xcode does a lot to make the class without our working for it. There are no constructors, setters or getters that need implementation, like Java or C++. Prior to XCode 4.4, you did need the @synthesize, but even that isn’t necessary anymore. It’s all automatic or not needed. Granted, you can make you own setters and getters, but it isn’t mandatory.

Python’s class definitions are quite interesting in that context:

#Objects_01
class PDPythonStuff:
    def __init__(self,a,b):
        self.a=a;
        self.b=b;
    def myFunction(self,a,b):
        return a + b*b

    def montyFunction(self):
        return self.a + self.b * self.b

# test implementation of the class
c=PDPythonStuff(5,25)
print('my Function =',c.myFunction(5,25))
print('my Function =',c.myFunction(4,25))
print('my Function =',c.montyFunction())
c.a = 4
print('my Function =',c.montyFunction())

Like defining functions, Python is super simple in defining classes. We don’t need to define what is public or private, or what is a class or instance method. With all those definitions missing, our code is a lot smaller. We start with a class operator name, then have a series of functions in the class. The first function among them __init__ is very important. As we saw above, Objective-C does have an init method, and can set beginning values for the instance. In Python __init__ is the constructor for the class. We do not have a header .h file in Python like Objective-C to declare what our properties are. Therefore we must declare their existence somewhere and the best place is in __init__.

Add the following function to the class:

    def montyFunctionToo(self):
        return self.a + self.d *self.d

Now add under the other print functions

print('my Function =',c.montyFunctionToo())

Save and run. You will get a error:
AttributeError: 'PDPythonStuff' object has no attribute 'd'

Nowhere did we define a what I would call a property in XCode, or attribute in Pythonspeak, called d. Python is angry at us for that. In the __init__ add:

self.d = 10

Save and run again, and things will work fine again. You do not have to put the initial value in the parameter list.

Note the first parameter in each def here is self. It is mandatory for methods of a class to have self as the first parameter in the definition. So we have

def myFunction(self,a,b):
        return a + b*b

We do not need self when we call the method:

print('my Function =',c.myFunction(4,25))

Note the def for a  function that has no parameters still has self.

  def montyFunction(self):
        return self.a + self.b * self.b
...
print('my Function =',c.montyFunction())

Now that we can make some classes, we can start to use them in Python. We’ll discuss more about classes and some cautions about them in our next entry.

One response to “from Apple to Raspberry Pi: Making Classes in Python”

  1. It’s really a nice and useful piece of info. I am happy that you shared this useful
    information with us. Please stay us informed like this.
    Thank you for sharing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: