What are magic methods in python? (AI) Flashcards

(9 cards)

1
Q

What are magic methods in Python?

A

Standardized way to add built-in behavior to user-defined classes

Also known as dunder methods.

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

Name a common use-case for magic methods related to string representation.

A
  • __str__
  • __repr__

__str__ is for end-users, while __repr__ is for developers.

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

What magic method is used for object initialization?

A

__init__

This method is called when an instance of a class is created.

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

Which magic methods control attribute access?

A
  • __getattr__
  • __setattr__
  • __delattr__

These methods manage how attributes are accessed, assigned, and deleted.

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

What magic method makes an instance callable?

A

__call__

Allows an instance to be called like a function.

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

Which magic methods define comparison operators?

A
  • __eq__
  • __lt__

__eq__ defines equality (==), while __lt__ specifies less than (<).

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

What magic methods are used for iteration?

A
  • __iter__
  • __next__

__iter__ returns an iterator, and __next__ retrieves the next item.

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

Which magic methods are involved in context management?

A
  • __enter__
  • __exit__

__enter__ sets up the context, and __exit__ cleans it up.

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

What magic methods handle numeric operations?

A
  • __add__
  • __sub__

__add__ is for addition (+), and __sub__ is for subtraction (-).

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