Objects, classes, methods Flashcards
what are Objects and Classes?
- everything in python is an object: value, function, variable, etc
- everytime we create a variable we are making a new object
- every object has a type or class associated with it (str, int, float, list etc)
- objects are instances of a class (type)
- ‘instance’ and ‘object’ used interchangeably
alex = Tutrle(0,0)
alex is instance of Turtle class
Object-Oriented Programming
Class (i.e Person)
Attributes (i.e name, age, city, gender)
Methods (i.e eat, study, sleep, play)
general form of a Class:
class CamelCase:
CONSTRUCTOR
def __init__(self, param1, param2, …)
…
body
METHOD
def method1(self, parameters):
body
Instantiate
creating (constructing) an instance of a class
i.e
alex = Turtle(0,0)
Methods (Functions)
- a function defined in a class
- when defining method, first parameter refers to instance being manipulated(self)
- method call automatically inserts an instance reference as first argument
- defining methods without self will not cause an error, error only occurs when u call function
def up(self): body
def goto(self, x, y): body
to call:
instance_of_class.method()
i.e
ben.up()
Attributes (Data)
- a variable bound to an instance of a class
alex = Turtle(0,0)
to access:
alex. x
alex. y
Constructor
- responsible for setting up the initial state of a new instance
def __init__(self, x, y):
self. x = x
self. y = y
__iniit__ method is automatically run during instantiation
self
- reference to the instance of the class
- at the time of designing the class we don’t know what these instance neames will be so use self
i.e urmom is self
Outside Class
urmom. attribute
urmom. method
Inisde Class
self. attribute
self. method
Encapsulation
- core of OOP is organization of the program by encapsulating related data and functions together on an object
- keeping data and the code that uses it in one place and hiding the details of exactly how they work tgt
Objects as Data Attributes of Classes
-objects are programmer-created data types that can be used just like other data types
i.e create a Sqaure class and use Point instances and attributes
class Square:
def __init__(self, x1, x2, y1, y2):
self. lower_left = Point(x1, y1)
self. upper_right = Point(x2, y2)
Printing Information
- to not have to write a print statement when we want to display attribute info
use: def __str__(self):
def __str__(self):
“””
(self) -> str
Return the coordinates of the Point
“””
return “(“ + str(self.x) + “,” + str(self.y) + “)”
my_point = Point()
print(my_point)
–> (0,0)