self
. Because they use self
, they require
an instance of the class in order to be used. For this reason, they're often
referred to as "instance methods".Class attributes are attributes that are set at the class-level, as opposed to the instance-level. Normal attributes are introduced in the
__init__
method, but some attributes of a class hold for
all instances in all cases. For example, consider the following definition of
a Car
object:class Car(object):
wheels = 4
def __init__(self, make, model):
self.make = make
self.model = model
mustang = Car('Ford', 'Mustang')
print mustang.wheels #prints 4
print Car.wheels #prints 4
A Car
always has four wheels
, regardless of the make
or model
. Instance
methods can access these attributes in the same way they access regular
attributes: through self
(i.e. self.wheels
). Static Methods:
Static methods are the methods that don't have access to
self.
Just like class attributes, they are methods that work without
requiring an instance to be present. Since instances are always referenced
through self
, static methods have no self
parameter.The following would be a valid static method on the
Car
class:class Car(object):
...
@staticmethod
def make_car_sound():
print 'VRooooommmm!'
No matter what kind of car we have, it always makes the same sound. To make it clear that this method should not receive
the instance as the first parameter (i.e. self
on "normal" methods), the
@staticmethod
decorator is used.Class Methods:
A variant of the static method is the class method. Instead of receiving the instance as the first parameter, it is passed the class. It, too, is defined using a decorator:
class Vehicle(object):
...
@classmethod
def is_motorcycle(cls):
return cls.wheels == 2
Class methods are for when you need to have methods that aren't specific
to any particular instance, but still involve the class in some way.
The most interesting thing about them is that they can be overridden by
subclasses.
No comments:
Post a Comment