[Tutor] Class definitions
dn
PythonList at DancesWithMice.info
Mon Jan 1 17:05:25 EST 2024
Are you training folk, or requiring in Code Reviews, the use of
parentheses in stand-alone class definitions (or not)?
The non-responsive fellow wrote a function-definition as:
def prnt:
(twice!) which is plainly incorrect because the def, the parentheses,
and the colon are all compulsory [as discussed, elsewhere] - even if the
parameter-list is empty.
funcdef ::= [decorators] "def" funcname [type_params] "("
[parameter_list] ")" ["->" expression] ":" suite
Whereas, a class-definition requires only the class and a colon. In this
case, parentheses are only needed to delimit an inheritance argument-list.
classdef ::= [decorators] "class" classname [type_params]
[inheritance] ":" suite
inheritance ::= "(" [argument_list] ")"
That said, and IIRC carrying-over from Python2, the inheritance
argument-list is separately optional. In other words, one may express an
empty set of parentheses. Accordingly, this old-timer's personal
habit/muscle-memory(?) is to type them quite unconsciously.
- or maybe some vague-idea that they just might be needed in-future in
the same way that we add commas after the last element of lists in case
of later additions-and-alterations?
Conversely: over the years, I've occasionally noted newcomers becoming
confused between function-definitions and class-definitions. Not between
function and class as constructs, but between (function) parameter-lists
and (class) inheritance argument-lists.
Accordingly, wondered if you feel there is virtue in writing class-names
without parentheses, and only moving to such syntax upon reaching more
advanced levels involving inheritance (and multiple-inheritance)?
Web.Ref:
https://docs.python.org/3/reference/compound_stmts.html
--
Regards,
=dn
More information about the Tutor
mailing list