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, withbasesuppercased.length()returning the number of bases.gc_content()returning the GC fraction rounded to 4 decimals, or0.0for an empty sequence.__repr__returning"Sequence(<name>, <length>bp)".
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | TP53 atggcc | Sequence(TP53, 6bp) 6 0.6667 |
| 2 | stdin | chr17 GGGGCCCC | Sequence(chr17, 8bp) 8 1.0 |
| 3 | stdin | test ATAT | Sequence(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().