Skip to main content
Engineering LibreTexts

14.7: Classes as Types

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    As we have seen, in Python, all variables have a type. And we can use the built-in dir function to examine the capabilities of a variable. We can use type and dir with the classes that we create.

    Code 14.7.1 (Python)
    class PartyAnimal:
       x = 0
       def party(self) :
         self.x = self.x + 1
         print(\"So far\",self.x)
    an = PartyAnimal()
    print (\"Type\", type(an))
    print (\"Dir \", dir(an))
    print (\"Type\", type(an.x))
    print (\"Type\", type(
    # Code:

    When this program executes, it produces the following output:

    Type <class '__main__.PartyAnimal'>
    Dir  ['__class__', '__delattr__', ...
    '__sizeof__', '__str__', '__subclasshook__',
    '__weakref__', 'party', 'x']
    Type <class 'int'>
    Type <class 'method'>

    You can see that using the class keyword, we have created a new type. From the dir output, you can see both the x integer attribute and the party method are available in the object.

    This page titled 14.7: Classes as Types is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.