""" objects.py Some object examples in python. See ./objects.js for a comparison Jim Mahoney | cs.marlboro.college | MIT License | Jan 2019 """ # --- a minimal object ------------ # First we have to define it with "class". # Then we can make one (i.e. "instantiate it") with its constructor. # # Note that unlike some languages (e.g. Java), # we can create new attributes after the class has been defined. class Minimal: # define the class """ A minimal class """ pass m = Minimal() # create an instance m.name = "John Min" # put some data into m print("m.name is {}".format( m.name )) # get that data out of m # --- an object with a method ---------- # Methods must be declared with the class. # The instance is referred to as "self" within the method, which is passed explicitly. # The method definition argument list must start with self, # but is not passed when the method is invoked. class HasMethod: # define the method in the class def set_name(self, name): self.name = name h = HasMethod() # create an instance h.set_name('John') # invoke it print("h.name is {}".format( h.name )) # --- an object constructor ----------- # Python has a special __init__ method whose arguments # define what can be specified when the object is created. class WithConstructor: # define the class def __init__(self, name, age): self.name = name self.age = age wc = WithConstructor('Sally', 21) # create an instance print("wc's name is {} and age is {}".format( wc.name, wc.age )) # --- inheritance --------- class Parent: def __init__(self, value): self.value = value def double_value(self): return 2 * self.value class Child(Parent): pass kid = Child(3) print("kid.value is {} and .double_value() is {}".format( kid.value, kid.double_value() ))