class Robot:
def greet(self):
return "Hello, I am a robot."
# Define a new function
def new_greet():
return "Hi! I'm your waifubot!"
# Change the method dynamically
robot_instance = Robot()
robot_instance.greet = new_greet
print(robot_instance.greet()) # Output: "Hi! I'm your waifubot!"
class CustomBot:
def __init__(self, action_func):
self.action = action_func # Set function dynamically
def perform_action(self, *args):
return self.action(*args) # Call the function with arguments
# Define a custom function
def greet(name):
return f"Hello, {name}!"
# Create an instance with a function passed in
bot = CustomBot(greet)
print(bot.perform_action("Alice")) # Output: "Hello, Alice!"
def create_and_use_global():
global counter # Declare the variable as global
if "counter" not in globals(): # Check if it exists first
counter = 0 # Initialize only once
print(f"Counter created: {counter}")
else:
counter += 1 # Modify the existing global variable
print(f"Counter updated: {counter}")
create_and_use_global()
create_and_use_global()
create_and_use_global()
print(f"Final counter value: {counter}") # Output: 2