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 created
2 def __init__(self, name):
# Store the name as an instance variable
3 self.name = name
4
# Methods are functions that belong to the class
# self is always the first parameter
5 def greet(self):
# Access instance variable with self.name
6 return f"Hello, {self.name}!"
7
# Create an instance of Person with name "Alice"
8p = Person("Alice")
# Call the greet method and print the result
9print(p.greet())

Output

Hello, Alice!
Practice typing this code

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

More Python examples at level 4

← Python typing practice