Simple Class in Python
Level 4142 keystrokes
This defines a Person class with a constructor and method, printing 'Hello, Alice!'. Classes are blueprints for creating objects.
Python code
# class keyword defines a new class (blueprint for objects)1class Person: # __init__ is the constructor, called when creating an instance # self refers to the instance being created2 def __init__(self, name): # Store the name as an instance variable3 self.name = name4 # Methods are functions that belong to the class # self is always the first parameter5 def greet(self): # Access instance variable with self.name6 return f"Hello, {self.name}!"7 # Create an instance of Person with name "Alice"8p = Person("Alice")# Call the greet method and print the result9print(p.greet())Output
Hello, Alice!
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 5)× 5_× 4"× 4:× 3.× 3,× 2=× 2!× 1{× 1