Classes Flashcards

(21 cards)

1
Q

Define class attribute

A
class Human:
  species = "H. sapiens"

WARNING - when using mutable types, single instance is shared by all the objects!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Define instance attribute

A
  def \_\_init\_\_(self, name):
    self.name = name
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Define private instance attribute

A
  def \_\_init\_\_(self, name):
    # Private (_ is only suggestion, not enforced in any way)
    self._age = 0
    # Private (\_\_ triggers  name mangling, field is renamed to _Human\_\_update to prevent collisions in child classes)
    self.\_\_update(iterable)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Define instance method

A
  def say(self, msg):
    return msg
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Define class method

A
  @classmethod
  def get_species(cls):
    return cls.species
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Define static method

A
  @staticmethod
  def grunt():
    return "*grunt*"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Define Getter, setter and deleter called age

A
  # Getter (access by obj.age)
  @property
  def age(self):
    return self._age

  # Setter
  @age.setter
  def age(self, age):
    self._age = age

  # Deleter
  @age.deleter
  def age(self):
    del self._age
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Construct new object of Human class

A

i = Human(name="Ian")

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Define struct (POCO) class in python

A
from dataclasses import dataclass

@dataclass
class Employee:
    name: str
    dept: str
    salary: int
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Initialize parent from derived class ctor

A

super().\_\_init\_\_(name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Check if sup is instance of class Human

A

isinstance(sup, Human);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Check if sup is derived from Human

A

issubclass(sup, Human);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Check type of sup

A

type(sup);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Define class Superhero that derives from Human

A
class Superhero(Human):
pass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Define class Superhero that derives from Human and Bat

A
class Batman(Superhero, Bat):
pass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Get the order in which classes are searched for an attribute or method.
What is the full name of that property?

A

Batman.\_\_mro\_\_

Method Resolution Order

17
Q

Define class as iterator

A
class Reverse:
    # Called by iter()
    def \_\_iter\_\_(self):
        return self

    # Iterator must have a next method
    def \_\_next\_\_(self):
        if self.index == 0:
            raise StopIteration
        return data;
18
Q

Make hashable dataclass (that can be used as map key for example)

A
@dataclass(frozen=True)
class ServerConfig:
  host: str
  port: int = 8080
19
Q

What are benefits of dataclass over reguklar class for simple structures

A

Can have order / be readonly

@dataclass(order=True, frozen=True)

Auto-generated \_\_repr\_\_

print(config)
# Output: ServerConfig(host='localhost', port=8080, active_plugins=['auth', 'cache'])

Easy conversion to dict (great for serialization)

print(asdict(config))

Built-in equality check (compares values, not identity)

assert config == ServerConfig("localhost", active_plugins=["auth", "cache"])
20
Q

What are slots in class, when and how to use them?

A
  • \_\_slots\_\_ is a class-level optimization that tells Python to not use a dynamic \_\_dict\_\_ for instance attributes.
  • Instead, it reserves a fixed amount of memory for a specific set of attributes.

```python
class SlottedClass:
# Explicitly declare which attributes this class can have
__slots__ = (‘x’, ‘y’)

def __init__(self, x, y):
self.x = x
self.y = y

obj = SlottedClass(10, 20)
obj.z = 99 # AttributeError: ‘SlottedClass’ object has no attribute ‘z’
~~~

  • High Cardinality: You are creating massive numbers of small objects (e.g., Points in a 3D mesh, Nodes in a large Graph, Rows in a custom DataFrame).
  • Strict Schema: You want to enforce a strict structure and prevent developers (or yourself) from accidentally adding typos as new attributes (e.g., self.nmae = “Jon”).
21
Q

What are trade-off and gotachas of using slots in class?

A
  • You cannot add new attributes to instances at runtime (unless you explicitly add \_\_dict\_\_ to slots).
  • Inheritance: Slots do not automatically propagate to subclasses. If class B inherits from slotted class A but doesn’t define \_\_slots\_\_ itself, B will have a \_\_dict\_\_.
  • Multiple Inheritance: You cannot inherit from multiple classes that both define non-empty \_\_slots\_\_ (layout conflict).