Python One Line Class

Do you hate those lengthy class definitions with __init__ and too many whitespaces and newlines? Python One-Liners to the rescue! Luckily, you can create classes in a single line—and it can even be Pythonic to do so! Sounds too good to be true? Let’s dive right into it!

Problem: How to create a Python class in a single line of code?

Example: Say, you want to create a class Car with two attributes speed and color. Here would be the lengthy definition:

class Car:

    def __init__(self, speed, color):
        self.speed = speed
        self.color = color

porsche = Car(200, 'red')
tesla = Car(220, 'silver')

# red

# silver

How do you do this in a single line of code?

Let’s have an overview first in our interactive Python shell:

Exercise: Create a third attribute seats and initialize it for both the Tesla and the Porsche car!

Method 1: type()

The type(name, bases, dict) function creates and returns a new object. It takes three arguments that allow you to customize the object:

  • name: this is the class name of the new object. It becomes the name attribute, so that you can use to access the argument value.
  • bases: this is a tuple of one or more tuple values that defines the base classes. You can access the content via the object.bases attribute of the newly-created object.
  • dict: this is the namespace with class attributes and methods definitions. You can create custom attributes and methods here. In case, you want to access the values later, you can use the object.__dict__ attribute on the newly-created object.

Here’s how you can use the type() function to create a new Car object porsche:

# Method 1: type()

# One-Liner
porsche = type('Car', (object,), {'speed': 200, 'color': 'red'})

# Result
# red

If you need to learn more about the type() function, check out our related article.

Related Article: How to Create Inline Objects With Properties? [Python One-Liner]

The type() function is little-known but very effective when it comes to creating object of various types. The only disadvantage is that you cannot reuse it—for example, to create another object. You’d need to use the same argument list to create a second object of the same type, which may be a bit tedious in some cases.

Method 2: Lambda Object + Dynamic Attributes

The lambda keyword is usually used to create a new and anonymous function. However, in Python, everything is an object—even functions. Thus, you can create a function with return value None and use it as a Car object.

Then, you add two dynamic attributes speed and color to the newly created object. You can one-linerize everything by using the semicolon syntax to cram multiple lines of code into a single line. Here’s how the result looks like:

# Method 2: lambda + dynamic attributes

# One-Liner
tesla = lambda: None; tesla.speed = 200; tesla.color = 'silver'

# Result
# silver

This method is a bit unnatural—and I’d consider it the least-Pythonic among the ones discussed in this article. However, the next one is quite Pythonic!

Method 3: Named Tuples

There also is an exciting data type in the collections module: named tuples.

from collections import namedtuple

# One-Liner
tesla = namedtuple('Car', ['speed', 'color'])(200, 'silver')

# Result
print(tesla.speed, tesla.color)
# 200 silver

The namedtuple object definition consists of two parts:

  • The first part of the expression namedtuple('Car', ['speed', 'color']) creates a new object with two attributes given in the list.
  • The second part of the expression associates the string 'value' to the tuple attribute 'property'.

This final method is efficient, clean, and concise—and it solves the problem to create a Python class in a single line of code because you can reuse your namedtuple “class” to create multiple instances if you want!

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!