python Flashcards
reverse python string
txt = “Hello World”
txt = txt[::-1]
print(txt)
Add list to class
class Person():
#self represents the object itself
def __init__(self, name):
self.name = name
self.books = []
def add_book(self, title): self.books.append(title)
python used most often to _____
Websites, data analysis & visualization, task automation.
Python is interpreted, meaning ____
it does not need to compile
Python passes parameters by ____
reference by default, but also by value
what is __init__
the first method of a class. when you instantiate an object it is automatically invoked to initialize members of a class.
remove whitespace from string
string.strip()
shuffle list
import random
random.shuffle(list1)
what does break do?
breaks out of the current loop
string slicing syntax
str[1:5]
index starts at 0, inclusive 1st field, exclusive 2nd field.
class creation
class Person:
def sayHello(self):
print(“Hello”)
create class instance and use method
p1 = Person()
p1.sayHello()
define class function that takes a parameter
class Person:
def add_one(self, x):
return x + 1
print(p1.add_one(5))
class init method purpose
method is called whenever an instance of it is created
init method syntax
def __init__(self):
pass
init method to create an object with a name by default
def __init__(self, name):
self.name = name
getter method
def get_name(self):
return self.name
setter method
def set_age(self, name):
self.name = name
make classes that are connected to each other (add person to course)
class Course:
def __init__(self, name):
self.name = name
self.people = []
def add_person(self, person): self.people.append(person)
inheritance is used when?
When classes have a lot in common. You only need to hard code the different parts in the classes and inherit the similar code.
how inheritance is implemented
You have subclasses take the parent class as a parameter. if Pet is the parent class and cat is a subclass, you’d do class Cat(Pet):
overriding in inheritance
subclass functions will override parent class methods with the same name
how to extend init in the parent class if you have an extra attribute you want to add (color)
if you have a Pet parent class with an init method that has a name parameter, the subclass will look like this:
class Cat(Pet):
def__init__(self, name, color):
super().__init__(name)
self.color = color
what is a class attribute
something you can access using the name of the class.
class Person:
num = 0
print(Person.num)
# displays 0