12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The following is a quick summary of the bare essentials of <strong>Python</strong> OOP. As you’llsee, <strong>Python</strong> classes are in some ways similar to both defs and modules, but they maybe quite different from what you’re used to in other languages.Class Objects Provide Default BehaviorWhen we run a class statement, we get a class object. Here’s a rundown of the mainproperties of <strong>Python</strong> classes:• The class statement creates a class object and assigns it a name. Just like thefunction def statement, the <strong>Python</strong> class statement is an executable statement.When reached and run, it generates a new class object, and assigns it to thename in the class header. Also, like defs, class statements typically run when thefiles they are coded in are first imported.• Assignments inside class statements make class attributes. Just like in modulefiles, top-level assignments within a class statement (not nested in a def) generateattributes in a class object. Technically, the class statement scope morphsinto the attribute namespace of the class object, just like a module’s globalscope. After running a class statement, class attributes are accessed by namequalification: object.name.• Class attributes provide object state and behavior. Attributes of a class objectrecord state information and behavior to be shared by all instances created fromthe class; function def statements nested inside a class generate methods, whichprocess instances.Instance Objects Are Concrete ItemsWhen we call a class object, we get an instance object. Here’s an overview of the keypoints behind class instances:• Calling a class object like a function makes a new instance object. Each time aclass is called, it creates and returns a new instance object. Instances representconcrete items in your program’s domain.• Each instance object inherits class attributes and gets its own namespace.Instance objects created from classes are new namespaces; they start out empty,but inherit attributes that live in the class objects from which they were generated.• Assignments to attributes of self in methods make per-instance attributes.Inside class method functions, the first argument (called self by convention) referencesthe instance object being processed; assignments to attributes of selfcreate or change data in the instance, not the class.466 | Chapter 23: Class Coding Basics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!