登录

Object-oriented Programming

Methods and Properties

Methods and properties can be assumed to be public unless otherwise stated. Where the access level is

relevant to the question, it will be explicit in the code using the keywords PUBLIC or PRIVATE.

//Example code:
PRIVATE Attempts : INTEGER Attempts ← 3

PUBLIC PROCEDURE SetAttempts(Number : INTEGER)
    Attempts ← Number
ENDPROCEDURE

PRIVATE FUNCTION GetAttempts() RETURNS INTEGER
    RETURN Attempts
ENDFUNCTION

Methods will be called using object methods, for example:

Player.SetAttempts(5)
OUTPUT Player.GetAttempts()

Constructors and Inheritance

Constructors will be procedures with the name NEW.

CLASS Pet
    PRIVATE Name : STRING
    PUBLIC PROCEDURE NEW(GivenName : STRING)
        Name ← GivenName
    ENDPROCEDURE
ENDCLASS

Inheritance is denoted by the INHERITS keyword; superclass/parent class methods will be called using the

keyword SUPER, for example:

CLASS Cat INHERITS Pet
    PRIVATE Breed: INTEGER
    PUBLIC PROCEDURE NEW(GivenName : STRING, GivenBreed : STRING)
        SUPER.NEW(GivenName)
        Breed ← GivenBreed
    ENDPROCEDURE
ENDCLASS

To create an object, the following format is used:

<object name> ← NEW <class name>(<param1>, <param2> ...)

For example:

MyCat ← NEW Cat("Kitty", "Persian")

Properties and methods are public by default, private properties and methods need only be preceded by two underscores __.

Constructor

class Pet:
	name = '' #public attribute
	def __init__(self, givenName):
		self.name = givenName
    def wow(self): #public method
        print('wow')

myCat = Pet('Jack')
print(myCat.name) #Jack

Inheritance

class Cat(Pet):
	__breed = '' #private attribute
	def __init__(self, givenName, givenBreed):
		self.name = givenName
        self.breed = givenBreed

myCat = Cat('Jack','Persian')
print(myCat.breed) #Persion
myCat.wow() #wow

登录