Object Oriented

Property

Python

 

Defining Property

Python 2.7
class Person:

  def __init__(self, name, age):
    self.name = name
    self.age = age

Properties are like variables.

Properties keep the state of the current object.

Properties in Python can be set on objects even after objects are created.

Here we are setting properties name and age as soon as the object is created.

The self parameter here points to the current object in the Class definition.

 

Accessing Properties

Python 2.7
person1 = Person('Sam', 21)

person1.name = 'Sarah'
theName = person1.name    # Sarah

You can access properties (attributes) of an object using the . operator.

The other way to access attributes in Python is by using getattr and setattr.

person1 = Person('Sam', 21);

setattr(person1, 'name', 'Sarah')
theName = getattr(person1, 'name', 'nothing')   # Sarah
 

self

Python 2.7
class Person:
  
  def __init__(self, name, age):
    self.name = name
    self.age = age
  
  def greet(self):
    print("Hi! I'm " + self.name)
  
  def birthday(self):
    self.age = self.age + 1

Class Methods in Python always get a reference to the current object in their first parameter on method calls.

This argument is conventionally named self, but it can be any name.

This is similar to this keyword in other Programming Languages.

It is recommended to always name the first method argument self.