Object Oriented Programming
Methods in Python
Methods are functions declared within a class. There are three types: instance, class, and static.
Instance methods have different implementation across all instances. They are called in relation to the current instance.
Class methods have the same implementation across all instances. They are called in relation to the instance passed in.
Static methods have the same implementation across all instances. They are not tied to a class instance.
Syntax
class ClassName(object):
#instance methods always take self as the first parameter
def instance_method(self, passed_params):
#code to execute
#the constructor is an instance method
def __init__(self, passed_params):
#assignments
#class methods always take a class instance as the first parameter
@classmethod
def class_method(cls, passed_params):
#code to execute
@staticmethod
def static_method(passed_params):
#code to execute
class_instance = ClassName()
#calling instance and class methods
class_instance.instance_method()
#calling static methods
ClassName.static_method()
Notes
Like variables, leading double underscores can be used to indicate that access level of the method is meant to be private.
Example
class Dog(object):
#class attribute
legs = 4
#instance methods
def __init__(self, breed):
self.breed = breed
def get_breed(self):
return self.breed
@classmethod
def get_legs(cls):
return cls.legs
@staticmethod
def make_noise():
return "*bark*!"
new_dog = Dog("Golden Retriever")
print ("I got a new dog. It is a {}".format(new_dog.get_breed()))
print ("It goes {}".format(Dog.make_noise()))
See Also
RelatedConstructors
Class Declaration and Structure
Functions
Classes - Python Documentation