Tuesday, November 20, 2018

First objects

Door class and tests

class Door:
    def __init__(self, number):
        self.number=number
        self.locked=True
        self.open=False
    
    def unlock(self):
        self.locked=False
    
    def lock(self):
        if self.open==False:
            self.locked=True
    
    def openDoor(self):
        if self.locked==False:
            self.open=True
    
    def closeDoor(self):
        self.open=False
        self.locked=True

    def __str__(self):
        if self.open==True:
            self.status="the door is open and unlocked"
        
        elif self.locked==False and self.open==False:
            self.status= "The door is unlocked and ready to open"
        else:
            self.status="the door is closed and locked"
    
        return self.status
        

def main():
    door=Door(3176)
    print ("lets unlock the door") 
    door.unlock()
    print(door)
    print ("let's open the door")
    door.openDoor()
    print(door) 
    print ("let's shut and lock it")
    door.closeDoor()
    print(door)

main()     

MSDie class

from random import randrange
class MSDie:
    def __init__(self, sides):
        self.sides=sides
        self.value=1

    def roll(self):
        self.value=randrange(1,self.sides+1)
    
    def getValue(self):
        return self.value
    
    def setValue(self, value):
        self.value=value

TestDie class (You must have an __init__.py file in the directory to be able to import.)

from die import MSDie
def main():
    d1=MSDie(12)
    d2=MSDie(12)
    d1.roll()
    d2.roll()
    print(d1.getValue())
    print(d2.getValue())

main()

No comments:

Post a Comment