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
age as soon as the object is created.
self parameter here points to the current object in the Class definition.
person1 = Person('Sam', 21) person1.name = 'Sarah' theName = person1.name # Sarah
You can access properties (attributes) of an object using the
The other way to access attributes in Python is by using
person1 = Person('Sam', 21); setattr(person1, 'name', 'Sarah') theName = getattr(person1, 'name', 'nothing') # Sarah
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