Python

Class (Python)

A class in Python is a blueprint for creating objects, defined with the class keyword.

This page covers Class in Python. For a language-agnostic introduction, see Class.

Defining a Class#

class Player:
    pass

pass is a placeholder that means “empty body”. By convention, class names use PascalCase: Player, OddsAndEvens, RockPaperScissors.

Adding a Constructor#

In Python, the constructor is a special method called __init__. It runs automatically when an object is created. The first parameter is always self — a reference to the object being created.

Comment (Python)

This page covers Comment in Python. For a language-agnostic introduction, see Comment.

A comment in Python is text the interpreter ignores. Python has one comment syntax: the single-line comment.

Single-line comment#

A single-line comment starts with # and continues to the end of the line.

# Everything on this line is a comment.
print("Hello, World!")

You can also write it inline, to the right of code:

print("Hello, World!")  # Everything to the right is a comment.

Multi-line comments#

Python has no dedicated block comment syntax. To comment across multiple lines, write a # at the start of each line:

Constructor (Python)

In Python, the constructor is a special method called __init__. It runs automatically when you create an object from a class.

This page covers Constructor in Python. For a language-agnostic introduction, see Constructor.

Defining __init__#

Like all instance methods in Python, __init__ takes self as its first parameter. Additional parameters receive the values passed when creating the object.

class Player:
    def __init__(self, name):
        self.name = name

self.name = name stores the argument on the object.

Method (Python)

A method in Python is a function defined inside a class using the def keyword.

This page covers Method in Python. For a language-agnostic introduction, see Method.

Defining a Method#

Every instance method in Python takes self as its first parameter. self is a reference to the object the method is being called on.

class Player:
    def greet(self):
        print("Hello!")

By convention, method names use snake_case: greet, play, get_score.

Return Values#

Use return to send a value back from a method. A method without a return statement returns None.