Python OOP: Properties & Constructors with Boobs!

Posted Jan 13, 2015

Today we're going to demonstrate the difference between setting properties within the constructor and outside of it with Python. Plus you get to learn a little bit about bra sizing.

We're working on a new CodeBabes Python course right now, so might as well blog about some OOP Python stuff.

In python, properties declared outside a method are class properties, not instance properties. This is different from most other languages. For instance in PHP, properties declared in the class are object members, unless specifically declared static.

Properties set outside __init__ in Python

# Setting defaults outside of constructor
class Boobs:

    bra_stats = {'torso': 32, 'cup': 'B', 'fruit': 'orange'}

    def __init__(self, cup = None, fruit = None):
        if cup && fruit:
            self.boob_stats['cup'] = cup
            self.bra_stats['fruit'] = fruit

average = Boob()
big = Boob('C', 'Grapefruit')

print average.bra_stats # {'torso': 32, 'cup': 'C', 'fruit': 'Grapefruit'}
print big.bra_stats # {'torso': 32, 'cup': 'C', 'fruit': 'Grapefruit'}


You'd think that average would output 'Orange', but since properties were set outside the __init__ function they are shared between all instances of the class, so when we created the 'big' object we changed the 'fruit' property all instances, so printing average now outputs 'Grapefruit'. Although it would be great if average were Grapefruit sized ;)

Properties set inside __init__ in Python

# Setting defaults in constructor.
class Boobs:

    def __init__(self, cup = None, fruit = None ):
        # Set defaults.
        self.bra_stats = {torso: 32, 'cup': 'B', 'fruit': 'Orange'}
        if size && fruit:
            self.bra_stats['cup'] = cup
            self.bra_stats['fruit'] = fruit

average = Boobs()
big = Boobs('C', 'Grapefruit')

print average.bra_stats # {'torso': 32, 'cup': 'B', 'fruit': 'Orange'}
print big.bra_stats # {'torso': 32, 'cup': 'C', 'fruit': 'Grapefruit'}


Since we set the properties inside the constructor (__init__) function, they are unique to any objects created (instantiated) with the Boobs Class. Now the outputs are correct. The average.bra_stats output B and Orange and the big.bra_stats output C and Grapefruit. The world is in equilibrium once again.