Here we go briefly through the basics of a class¶
Here we get a brief introduction to classes and how we can create them once and use anywhere! Simply put: classes have functions,and they encapsulate and collect related bits of useful information. And you can put related classes and functions in a file and give it a name, and we call that a module, which you can then import for your own work.
So actually, creating classes, creating functions, creating modules, it's all really easy. It's all just Python, and it's all just reusing a couple of concepts that we've seen a bunch of times in this series. So functions for encapsulating and naming useful bits of work,classes for encapsulating and naming related bits of functionality, and then modules to store a bunch of classes and functions. With all this you'll get a feel for when it makes sense to write functions, when it makes sense to right classes, and when it makes sense to create your own modules.
class greeting(object):
def hello(self):
print('Hi there!')
def goodbye(self):
print('Goodbye!')
g = greeting()
g.hello()
g.goodbye()
g2 = greeting()
g2.hello()
g2.goodbye()
Hi there! Goodbye! Hi there! Goodbye!
g2 = greeting()
g2.hello()
g2.goodbye()
Hi there! Goodbye!
class greeting(object):
def __init__(self, name): #is called whenever a new instance of a class is created
self.name = name
def hello(self):
print('Hi there! ' + self.name)
def goodbye(self):
print('Goodbye! ' + self.name)
g = greeting("Tarry")
g.hello()
g.goodbye()
g2 = greeting("Jessica")
g2.hello()
g2.goodbye()
Hi there! Tarry Goodbye! Tarry Hi there! Jessica Goodbye! Jessica
import random
class Die(object): # it inherist an object
def roll(self):
return random.randint(1, 6)
d = Die()
print(d.roll())
print(d.roll())
print(d.roll())
1 3 5
import random
class Die(object): # it inherist an object
def __init__(self, sides):
self.sides = sides
def roll(self):
return random.randint(1, self.sides)
print("D1 rolls: ")
d = Die(6)
print(d.roll())
print(d.roll())
print(d.roll())
print("D2 rolls: ")
d2 = Die(20)
print(d2.roll())
print(d2.roll())
print(d2.roll())
D1 rolls: 4 3 6 D2 rolls: 8 10 17
import random
class Deck(object):
def shuffle(self):
suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']
ranks = ['1','2','3','4','5','6','7','8','9','10', 'Jack', 'Queen', 'King', 'Ace']
self.cards = [] #Giving it self exposes is to the rest of the class for usage
for suit in suits:
for rank in ranks:
self.cards.append(rank + ' of ' + suit)
random.shuffle(self.cards)
def deal(self):
return self.cards.pop()
d = Deck()
d.shuffle()
print(d.deal())
print(d.deal())
print(d.deal())
5 of Clubs Ace of Clubs 9 of Diamonds