============================================= 7: Class, Methods and Constructors ============================================= Summary ============ - Unlike in other languages, in Python a class is an object - A class is a callable, which means it can be called like a function - When called as a function a class returns an instance - At its simplest, an instance has no attributes - Any attributes you try to access on the instance are resolved by attributes on the class object - If you assign to an attribute then it is created as an instance attribute - Function attributes defined on the class object are converted into method objects when accessed via an instance - Methods call the function object using self, the instance, as the first parameter - What this means is that you write function attributes with an explicit self parameter, but when you call a methods you do not specify self - Methods are bound to their instance when first accessed - This is a form of early binding - In addition to instance methods, you can also create static and class methods - The initializer __init__ can be used to add attributes to an instance and to initialize them - You can create multiple constructors using class methods - In Python it makes sense to place all methods in the class body and all data attributes in the __init__ - This allows methods to be shared by all instances and data to be unique to each instance Program ============ .. literalinclude:: programs/chapterSeven.py :language: python Program Output ================= .. code-block:: console (docs-env) root@BMitchellLTOP:~/git/sphinx_students/source/programming_lang/book/programs# python3 chapterSeven.py Student is an object: Is Student callable? True Type of student1: School name (student1): Spencerport High School School name (student2): Spencerport High School Hi, I'm Brayden, I'm 18 years old and my GPA is 3.8. Bound method: > Calling bound method: Hi, I'm Brayden, I'm 18 years old and my GPA is 3.8. Hi, I'm Alex, I'm 17 years old and my GPA is 3.6. Is student1 honor roll? True Hi, I'm Jordan, I'm 19 years old and my GPA is 3.9. Accessing class attribute via instance: Spencerport High School After overriding: student1 school: Different School student2 school (still class attribute): Spencerport High School Class school name: Spencerport High School