1/22
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
create a class
Use the keyword class followed by a capitalized class name (each word is capitalized) and a : Then indent and define attributes and methods underneath.
class Dog:
»»»def __init__(self, breed, age):
»»»»»self.breed = breed
»»»»»self.age = age
»»»def method(self):
»»»»»return or print whatever
def __init__(self, parameters):
Initializer. Parameters go in parentheses; first is self, then optional parameters.
self
The first parameter in the __init__ method is a variable that refers to an instance
__init__ body
Where you initialize instance attributes, typically assigning parameters to self.attribute.
def __init__(self, age)
»»»self.age = age
Constructor
A method that creates and initializes an object (the __init__ method).
Creating an instance
instance_variable = ClassName(‘argument1’, argument2)
Python passes the self argument for you so only supply the needed parameters
Access attributes
Use dot notation
instance.attribute
Methods
functions that belong to a class. They define the behavior of objects created from the class. Always include self as first parameter.
Call a method
Use instance.method() if self is the only parameter
Class attributes
Shared data for all instances of a class. It’s not in any of the functions
Instance methods
uses self to access the instance attribute
Class
A blueprint for how objects look and behave.
self meaning
actual instance of the class that just makes sure that all the data sticks to the correct instance
Dot notation
Used to access methods or attributes:
instance.attribute
instance.method()
Encapsulation
make data private from client code.
Leading underscore convention
beginning an attribute with a single or double underscore means it’s private
_attribute
__attribute
def __add__(self, other):
same as + operator. It takes the current and other instance. Overloads + to define how two instances of a class should be added.
ClassName( ) is used inside the method because:
You must return a brand new ClassName that represents the sum.
You should not change the original instances.
operator overloading
Allows custom classes to define behavior for operators like +, *, [ ].
Calling __add__
Use instance1 + instance2.
def __iadd__(self, other):
same as +=. Modifies the self object so it equals the sum of self + other
Calling __iadd__
Use instance1 += instance2
def __repr__(self):
When defined in a class, the method returns a string representation of an instance
Calling __repr__
Use
print(repr(instance))
print(instance)