pythonforbio.
[WASM idle]
Python Basics12/12

Classes

Starting sandbox…
Intermediatepuzzle3 tests

A class groups data and the functions that work on it. You will read classes constantly in Biopython and hgvs, even if you write few of your own.

class Variant:
    def __init__(self, chrom, pos, ref, alt):
        self.chrom = chrom
        self.pos = pos
        self.ref = ref
        self.alt = alt

    def is_snv(self):
        return len(self.ref) == 1 and len(self.alt) == 1


variant = Variant("chr17", 7676154, "G", "A")
print(variant.chrom, variant.pos)
print(variant.is_snv())

__init__ runs when the object is created. self is the object itself, and is the first parameter of every method.

repr

Without __repr__, printing an object shows its memory address. Defining one makes objects readable.

class Variant:
    def __init__(self, chrom, pos):
        self.chrom = chrom
        self.pos = pos

    def __repr__(self):
        return f"Variant({self.chrom}:{self.pos})"


print(Variant("chr17", 7676154))

Class attributes

An attribute defined on the class is shared by every instance. An attribute assigned in __init__ belongs to one instance.

class Variant:
    build = "GRCh38"

    def __init__(self, chrom):
        self.chrom = chrom


print(Variant("chr17").build, Variant("chr1").build)

Dataclasses

dataclass writes __init__ and __repr__ for you.

from dataclasses import dataclass


@dataclass
class Variant:
    chrom: str
    pos: int
    ref: str
    alt: str


print(Variant("chr17", 7676154, "G", "A"))

Task

Write a Sequence class with:

  • __init__(self, name, bases) storing both, with bases uppercased.
  • length() returning the number of bases.
  • gc_content() returning the GC fraction rounded to 4 decimals, or 0.0 for an empty sequence.
  • __repr__ returning "Sequence(<name>, <length>bp)".

Test cases · 3

#viainputexpected stdout
1stdinTP53 atggccSequence(TP53, 6bp) 6 0.6667
2stdinchr17 GGGGCCCCSequence(chr17, 8bp) 8 1.0
3stdintest ATATSequence(test, 4bp) 4 0.0

Hints · 2

01Hint

Uppercase in __init__ so every method can assume uppercase bases.

02Hint

length() can be called from gc_content() as self.length().

starter

No output yet — run the code to populate this drawer.

Modules and Importsend of path