14.7: Classes as Types

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    14.7: Classes as Types

    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)
    %%python3
    
    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(an.party))
    
    # Code: http://www.py4e.com/code3/party3.py
    
    

    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 was last modified on Fri, 10 Sep 2021 02:10:03 GMT and 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.