Back to the topic

The mark scheme starts on a new page, so you can print pages one and two for a student and keep the last page yourself. Everything prints in black on white whichever theme you are using.

Python · Advanced 4

Special Methods, Dataclasses and Type Hints

Section A: 10 multiple choice questions, 10 marks. Section B: 5 written questions, 21 marks. Total 31 marks.

Name

Class

Date

Mark  / 31

Section A

Circle the letter of the correct answer. One mark each.

  1. 1Which special method is called by print(obj)?1
    1. A__repr__ only
    2. B__show__
    3. C__str__
    4. D__print__
  2. 2Which special method makes a + b work for objects of your own class?1
    1. A__sum__
    2. B__plus__
    3. C__concat__
    4. D__add__
  3. 3What is needed for len(obj) and obj[0] to both work on your own class?1
    1. A__len__ and __getitem__
    2. B__size__ and __index__
    3. C__call__
    4. D__iter__ only
  4. 4What is the point of __repr__?1
    1. AAn unambiguous text form for programmers, ideally showing how to rebuild the object
    2. BTo copy the object
    3. CTo print a friendly message for users
    4. DTo compare two objects
  5. 5What does a property allow a class to do?1
    1. AStop a class being inherited
    2. BRun code when an attribute is read or assigned, without changing how it is used
    3. CMake an attribute constant
    4. DMake an attribute private
  6. 6What does the @dataclass decorator generate?1
    1. AA test for the class
    2. BA database table
    3. CA copy of the class
    4. D__init__, __repr__ and __eq__ from the annotated fields
  7. 7Why use an Enum for the states of a traffic light instead of strings?1
    1. AStrings cannot be compared
    2. BA misspelt name is an error, and the set of values is fixed
    3. CEnums run faster
    4. DEnums use no memory
  8. 8Python is run with this function: def f(x: int) -> int: return x * 2 and called as f('ha'). What happens?1
    1. AIt returns None
    2. BIt returns 'haha', because hints are not enforced
    3. CA SyntaxError is raised
    4. DA TypeError is raised
  9. 9What does a Protocol such as Speaker describe?1
    1. AA class that every other class must inherit from
    2. BA rule for naming variables
    3. CWhat methods an object must have, whatever its class
    4. DHow to send data over a network
  10. 10What does first, *rest = [1, 2, 3, 4] give rest?1
    1. A[2, 3, 4]
    2. B[3, 4]
    3. C2
    4. D[1]

Section B

Answer in the space provided. The number of marks tells you how many separate points to make.

  1. 1ExplainExplain the purpose of the special methods __str__ and __repr__ in a Python class.4
  2. 2WriteWrite a class called Vector with a constructor that takes two numbers, x and y, and stores them. Add a method so that two Vector objects can be added using the + operator, giving a new Vector whose x and y are the sums of the x and y values of the two vectors.4
  3. 3ExplainA programmer has an attribute called age in a class. Explain what a property is, and why the programmer might replace the attribute with a property.4
  4. 4DescribeDescribe two benefits of using a dataclass instead of a normal class for a class that is mostly used to store data.3
  5. 5DiscussA team is deciding whether to add type hints to a large Python program. Discuss the advantages and disadvantages of doing so.6

Mark scheme

Section A

1C2D3A4A5B6D7B8B9C10A

Section B

1 Explain the purpose of the special methods __str__ and __repr__ in a Python class. 4

One mark for each of the following, to a maximum of 4.

  • __str__ returns a readable text version of the object, for the user
  • It is used by print() and str()
  • __repr__ returns an unambiguous text version of the object, for the programmer (debugging)
  • It is used by repr() and when objects are shown in a list, and ideally shows how to recreate the object

Model answer. The __str__ method returns a readable text version of the object, intended for the user, and it is the one used by print() and str(). The __repr__ method returns an unambiguous text version intended for the programmer when debugging, and ideally it looks like the code needed to recreate the object. It is used by repr(), by the interactive prompt, and when objects are shown inside a list.

2 Write a class called Vector with a constructor that takes two numbers, x and y, and stores them. Add a method so that two Vector objects can be added using the + operator, giving a new Vector whose x and y are the sums of the x and y values of the two vectors. 4

One mark for each of the following, to a maximum of 4.

  • A class with an __init__ method taking x and y
  • The values are stored as attributes (self.x and self.y)
  • Defines __add__ with a parameter for the other vector
  • Returns a new Vector made from the two sums

Model answer.

Python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

total = Vector(1, 2) + Vector(3, 4)
print(total.x, total.y)

The constructor stores x and y as attributes. The special method __add__ is called when the + operator is used with a Vector on the left. It builds and returns a new Vector whose x and y are the sums of the two vectors' values. Here the result is a Vector with x of 4 and y of 6.

3 A programmer has an attribute called age in a class. Explain what a property is, and why the programmer might replace the attribute with a property. 4

One mark for each of the following, to a maximum of 4.

  • A property is a method that is accessed like an attribute (without brackets)
  • It runs code when the value is read or assigned
  • This allows the value to be validated, for example rejecting a negative age
  • Code that uses the class does not need to change, because it is used in the same way as before

Model answer. A property is a method that is accessed like an attribute, without brackets. It runs code whenever the value is read or assigned. The programmer might replace age with a property so that the value can be validated when it is set, for example by rejecting a negative age. Code that uses the class does not need to change, because the age is read and assigned in exactly the same way as when it was a plain attribute.

4 Describe two benefits of using a dataclass instead of a normal class for a class that is mostly used to store data. 3

One mark for each of the following, to a maximum of 3.

  • The __init__ method (constructor) is generated automatically from the fields, so less code needs to be written
  • Other methods such as __repr__ and __eq__ are also generated, giving a readable output and comparison of the objects
  • Options such as frozen and order make the objects immutable or sortable with one word

Model answer. A dataclass generates the __init__ method automatically from the fields, so a lot less code has to be written. It also generates methods such as __repr__ and __eq__, so the objects print readably and can be compared without writing those methods. Options such as frozen=True, which makes the objects immutable and hashable, and order=True, which makes them sortable, can be added with one word.

5 A team is deciding whether to add type hints to a large Python program. Discuss the advantages and disadvantages of doing so. 6

One mark for each of the following, to a maximum of 6.

  • Type hints document what types each function expects and returns
  • A checker such as mypy can find type errors before the program is run
  • Editors can use them to give better auto-completion and warnings, helping developers
  • Disadvantage: Python does not enforce them, so wrong types can still be used while the program runs
  • Disadvantage: extra code and effort to write and keep up to date, and hints that are wrong are misleading
  • A reasoned conclusion: worthwhile in a large program with several developers, if a checker is used

Model answer. Type hints document what type each function expects and returns, which makes a large program easier for a team to understand. A checker such as mypy can use them to find type errors before the program is run, and editors can use them to give better auto-completion and warnings. The disadvantages are that Python does not enforce them, so a value of the wrong type can still be used when the program runs, and that they take extra effort to write and keep up to date, and hints that are out of date or wrong are misleading. For a large program with several developers, type hints are worthwhile, provided a checker is run regularly so that they are kept correct.