11-3. Attributes and Methods

When we use classes and objects in Python to represent a software process, we can create a program that mimics or handles tasks related to software.

  • Attributes (or variables): These are like characteristics of the process. They hold information about the process.
  • Methods (or functions): These are like actions the process can perform.

When we create an object of the Process class, it represents one specific software process in action. This object has its own set of values for each attribute (characteristic) and can perform actions defined by the methods in the class.

Here's an example to make it clear:

Define a Class: Think of it as creating a blueprint for a software process.

class Process:
def __init__(self, name, id):
self.name = name # Attribute: name of the process
self.id = id # Attribute: id of the process

def start(self):
print(f'Process {self.name} with ID {self.id} is starting.')

def stop(self):
print(f'Process {self.name} with ID {self.id} is stopping.')

Create an Object: This is like making a specific process using the blueprint.

my_process = Process("Data Analysis", 101)

Use the Object: We can now use this object to perform actions.

print(my_process.name) # Output: Data Analysis
print(my_process.id) # Output: 101
my_process.start() # Output: Process Data Analysis with ID 101 is starting.
my_process.stop() # Output: Process Data Analysis with ID 101 is stopping.

Putting It All Together

Here's the complete code for our Process class example:

class Process:
def __init__(self, name, id):
self.name = name # Attribute: name of the process
self.id = id # Attribute: id of the process

def start(self):
print(f'Process {self.name} with ID {self.id} is starting.')

def stop(self):
print(f'Process {self.name} with ID {self.id} is stopping.')

def main():
my_process = Process("Data Analysis", 101)
print(my_process.name) # Output: Data Analysis
print(my_process.id) # Output: 101
my_process.start() # Output: Process Data Analysis with ID 101 is starting.
my_process.stop() # Output: Process Data Analysis with ID 101 is stopping.

if __name__=="__main__":
main()