OOP in Python Flashcards
What are the two main things every class has?
Attributes and Methods
What is the syntax of creating a class in Python
class <name>:</name>
What is a constructor? How is it written?
A constructor is a method that is called when an object is created
def __init__(self):
you can add more parameters
How do I make an attribute of the class?
How do I make it private?
self.variable self.\_\_variable
What happens when you try to access private attributes?
AttributeError
What is a crucial parameter that all methods of a class must have (unless it is static)?
def <func> (self)
the 'self' parameter</func>
What is a static method?
It is a method that can be called with the need of an object, mainly used for class utilities:
@staticmethod
def <func_name>():</func_name>
called using class name
<class>.<func>()
</func></class>
What if I want the parameters to be unchangeable (read-only)?
@property
def <var>(self):
return self.\_\_<var></var></var>
How to override the string representation method?
def __str__(self):
output = ‘ ‘
return output