3 min read•june 24, 2024
are fundamental to Python classes, allowing objects to interact with their own data. They define behaviors specific to each instance, accessing and modifying attributes using the '' keyword.
These methods come in various types, including constructors, regular instance methods, class methods, and static methods. Each serves a unique purpose, from initializing objects to performing operations on the class itself or providing utility functions.
[__init__()](https://www.fiveableKeyTerm:__init__())
special instance method called when creating new instance of class
self
refers to instance being createdself
separated by commasself.attribute_name = parameter_name
self.name = name
assigns value of name
parameter to name
attribute of instance=
operator after parameter name (def __init__(self, name, age=0):
)self
keyword
self.attribute_name
refers to attribute of current instanceself.attribute_name
changes value of attribute for that specific instance
self.name = "New Name"
changes name
attribute of instance to "New Name"
ClassName.attribute_name
refers to class attributeClassName.attribute_name
changes value of attribute for all instances of class
Car.wheels = 5
changes wheels
attribute for all instances of Car
classself.attribute_name
refers to instance attribute, overriding class attribute for that instanceself
as first parameter referring to instance on which method is calledself
def drive(self): self.speed += 10
increases speed
attribute of instance by 10
[@classmethod](https://www.fiveableKeyTerm:@classmethod)
decorator and operate on class itself
[cls](https://www.fiveableKeyTerm:cls)
as first parameter referring to classcls
@classmethod def from_string(cls, car_str): ...
creates instance of class from string representation[@staticmethod](https://www.fiveableKeyTerm:@staticmethod)
decorator and do not have access to instance or class attributes
self
or cls
as parameters@staticmethod def miles_to_kilometers(miles): return miles * 1.60934
converts miles to kilometers without needing instance or class