Phython Study Notes-a preliminary understanding of the class, phython Study Notes
Class is the core of object-oriented programming. It plays the role of relevant data and logical containers. They provide blueprints for creating instance objects. The python language does not require Object-Oriented Programming (different from JAVA). Here is a simple example.
How to define a class
class Classname(base_class[es]): "optional documentation string" static_menber_declarations
method_declarations
You can use the Class keyword to define a Class and provide an optional server or base Class. If there is no suitable Class, you can use the object Class.
Example:
class FooClass(object): """my very frist class:FooClass""" version=0.1 def _init_(self,nm='Jack Franklin'): """Constructor""" self.name=nm print 'Created a class instance for',nm def showname(self): """display instance attribute and class name""" print 'Your name is',self.name print 'My name is',self._class_._name_ def shoever(self): """"display class(static)attributr""" print self.version def addMe2Me(self,x): return x+x
Note that after an instance of a class is created, the _ init _ () method is automatically executed, similar to the constructor in JAVA.
What is self? It is a reference of the class instance itself, which is equivalent to this in other languages.
How to create a class instance:
>>>foo1=FooClass()Created a class instance for Jack Franklin>>>fool.showname()Your name is Jack FranklinMy name is _main_.FooClass>>>print foo1.addMe2Me(5)10