Object Oriented Programming Flashcards

1
Q

Objects as data structures

A

Object = state + behavior
State and behavior bundled together
Encapsulation - bundling data with code operating on it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

classes

A

Blueprint for objects outlining possible states and behaviors, doesn’t actually contain any data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Objects

A
Every object has a class
Use type() to find the class
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

State

A

Attributes - variables
Import numpy as np
A = np.array([1,2,3,4])

#shape attribute
A.shape
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Behavior

A
Methods - > functions
Import numpy as np
A = np.array([1,2,3,4])
#reshape method
A.reshape(2,2)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Function of list all attributes and methods

A

Dir(a)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Add methods to a class

A
Class customer:
     Def identify(self,name):
          Print(“I am Customer” + name)
Use self as the 1st argument in method definition
Method definition = function definition within a class
Ignore self when calling method on an object
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is self?

A

Classes are templates, how to refer data of a particular object?
Self is a stand-in for a particular object used in class definition, should be the first argument of any method
Python will take care of self when method called from an object
Cust.identify(“Laura”) will be interpreted as Customer.identify(cust,”Laura”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Class example

A
Class Customer:
    Def set_name(self, new_name):
        Self.name = new_name
#self.name = name creates an attribute called name and assigns to it the value of the name parameter
    Def identify(self):
        Print(“I am Customer” + self.name)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Constructor

A
\_\_init\_\_() method is called every time an object is created
Def \_\_init\_\_(self,name):
    Self.name = name

Create all attributes in the constructor and not throughout the class definition, attributes are created when the object is created

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Instance-level data

A

Name, salary were instance attributes
Self binds to an instance

Instance is an object that is built from a class and contains real data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Class level data

A
Data shared among all instances of a class 
Define a class attribute right after class
Use classname.global attribute to call it
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Class methods

A

Methods are already shared; same code for every instance can’t use instance level data

Class MyClass:
@classmethod
Def my_awesome_method(cls,args…)
Use cls instead of self

Can’t use instance attributes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Alternative constructors

A
@classmethod
Def from_file(cls,filename):
    With open(filename, ‘r’) as f:
        Name = f.readline()
    Return cls(name)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is OOP?

A

Structuring a program by bundling related properties and behaviors into individual objects

  • properties like a name, age, and address
  • behaviors such as walking, talking, running
  • relations between things
    Objects are at the center of the object-oriented programming in Python, not only representing data but also the overall structure of the program
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

__init__()

A

__init__() sets the initial state of the object by assigning the values of the object’s properties - initialized each new instance of the class

First parameter will always be a variable called self
Instance is automatically passed to the self parameter when a new class instance is created
So new attributes can be defined on the object
17
Q

__str__()

A

If you want to print something, use __str__(self)

Def \_\_str\_\_(self):
     Return f”{self.name} is {self.age} years old”
18
Q

Class inheritance

A

Use old code and add new functionality to the old to create new class

Class MyChild(MyParent):

MyParent: class whose functionality is being extended/inherited
MyChild: class that will inherit the functionality and add more

Child class has all the parent data, don’t have to define in the new class if it is already in the parent data

19
Q

Add new functionality to child class

A
Class SavingsAccount(BankAccount):
    def \_\_init\_\_(self, balance, interest_rate):
        BankAccount.\_\_init\_\_(self,balance) # self is a SavingsAccount but also a BankAccount

Add more functionality by defining new methods
Use data from both parent and child class

Can change the signature(add parameters)
Use Parent.method(self,args…) to call a method from the parent class

20
Q

Operator overloading

A

__eq__() called when 2 objects of a class are compared using ==

Custom comparison code (self and other) return a boolean value, true or false
There are not eq, greater or equal, less than, etc

__hash__ - use objects as dictionary keys and in sets

21
Q

Str and repr classes

A

__repr__() - repr(obj), printing in consol, formal, for developer, reproducible representation, fallback for print
__str__() - print(obj), str(obj) - informal for end user, string representation

22
Q

Except order

A

List except blocks in the increasing order of specificity - children before parents so that the children exception will be called in the parent except block

23
Q

Polymorphism

A

Using a unified interface to operate on objects of different classes

For example, a method to withdraw from a batch of different accounts, if the accounts fall in different classes but all have the method withdraw, python can withdraw from any object that has a withdraw method

24
Q

Liston substitution principle

A

no LSP no inheritence

Base class should be interchangeable with any of its subclasses without altering any properties of the programs

Syntactically - function signatures are compatible - arguments and returned values
semantically - state of the object and the program remains consistent (subclass method doesnt’ strengthen input or weaken output conditions, no additional exceptions)
25
Q

Restricting access

A

Class data is public

26
Q

Naming convention: internal

A

Obj._att_name, obj._method_name()

  • starts with a single _ => “internal”
  • not a part of the public API
  • internal details of implementation
  • as a class user: “don’t touch this”
  • i.e a helper method that checks validity of an attribute’s value but isnt’ considered part of class’s public interface
27
Q

Naming convention: pseudo private

A

Obj.__atrr_name, obj.__method_name()

  • starts but doesn’t end with __ —> “private”
  • not inherited
  • name mangling: obj.__atr_name is interpreted as obj._MyClass__attr_name
  • double leading underscores are used for attributes that should not be inherited to avoid name clashes in child classes
  • a “version” attribute that stores the current version of the class and shouldn’t be passed to child classes, who will have their own versions
28
Q

Control attribute access

A

Make attributes read only
Restricted and read-only
For data frames, you can’t just change the number of columns or the shape of it if it doesn’t adhere to the dataframe structure

29
Q

How to control attribute access

A

Use “protected” attribute with leading _ to store data

1) define constructor (__init__)
2) use @property on a method whose name is exactly of the restricted attribute; return the internal attribute
Def salary(self):
Return self._salary
3) to define how an attribute is set, use @attr.setter on a method attr() that will be called on obj.attr = value

Method with the property decorator returns the data and the method with salary dot setter decorator implements validation and sets the attribute

30
Q

Add @attr.getter

A

Use for the method that is called when the property’s value is retrieved