You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
much faster than equivalent list operations because they don't need to maintain an order
Making Sets:
#enclose within curly bracescast= {"Luigi", "Gumbys", "Spiny"}
#convert any list into a setnames= ["Luigi", "Gumbys", "Spiny"]
cast=set(names)
#to make an empty set, do not use {}cast=set()
numberOfCharacters=len(cast) #here would be 0#to access elements, can't use a set positionprint("The cast of characters include:")
forcharacterincast:
print(character)
#sets are mutable, so you can use the .add() and .discard() methodscast.add("Arthur")
cast.discard("Arthur")
cast.clear() #removes everything
a set is a subset of another set if every element occurs in the second set
first set.issubset("the second set") -> checks whether the first set is a subset of the second set
set1.union(set2) === contains elements of both sets with no duplicates
set1.intersection(set2) === contains the elements that are in both sets
set1.difference(set2) === new set that has the elements that aren't in set2
NOTE: use sets when managing a collection of unique items -> over 10 times faster than using lists
Dictionaries:
a container that keeps associations between keys and values
keys are unique, but a value can be associated with several keys
favColours= {
"Romeo": "Green",
"Adam": "Red",
}
oldFavColours=dict(favColours)
#creates a duplicate of favColours```python
not sequence-type, no indexes or position
can only access a value by its associated key
defaults keys:
number=contacts.get("Fred", 411)
print(number)
#if Fred doesn't exist, 411 is default
Editing Dictionaries:
contacts["John"] = 4578102 === adds a key "John" and value of 4578102
contacts["John"] = 2228102 === changes the value of "John"
contacts.pop("John") === removes the entire item, key and value -> returns the value so you can store it
Iterating over Dictionaries:
forkeyincontacts:
print(key, contacts[key])
#shows the keysforitemincontacts.items():
print(item[0], item[1])
#the .items() method returns a sequence of tuples
MODULAR PROGRAMMING:
Separates files making it easier to modify a certain aspect
can import modules
OBJECTS AND CLASSES
a class describes a set of objects with the same behaviour
each object has its own methods
Methods: -> public
defining methods is almost the same as a function
the method has to be in the class definition
the first argument has to be called self
methods fall in two categories:
accessor methods:
gets info from the object without changing
mutator methods:
usually take a parameter that will change an instance variable
changes the value
Making and Using:
classCashRegister:
#Adds an item to this cash registerdefaddItem(self, price):
#Method bodydefgetTotal(self):
#Method bodyregister1=CashRegister()
#Constructs a CashRegister objectregister1.addItem(1.95) #calls the method
each object has separate instance variables
the variables are unique to that object
use _ to start private instance variables and methods
the constructor:
uses the special name _ init _
this is where the instances are initialized
only one constructor per class
def__init__(self):
self._itemCount=0self._totalPrice=0def__init__(self, initialBalance=0.0):
self._balance=initialBalance#is no value is passed to the constructor, the default 0 will be used
calling methods within another method
use self.method()
class variables
defined before the init method
Inheritance
#dave's car is a subclass of all vehiclesclassdavesCar(vehicle)
def__init__(self):
. . .
Hierarchies:
superclass: a generalized class that encompasses other classes
subclass: a more specialized class
Subclasses:
inherit:
all methods (unless overridden)
all instance variables
can:
add new instance variables
add new methods
change the implementation of inherited methods
use the super() function in place of self when referring to the super class (ex. using superclass methods)
the superclass constructor should be called before the subclass defines its own instance variables