Python implementation class creation and use example, python example
This article describes how to create and use Python implementation classes. We will share this with you for your reference. The details are as follows:
# Coding = utf8 # In order to make Division always return the real operator, no matter whether the operand is an integer or floating point type. The from _ future _ import division ''' class is the core of object-oriented programming and plays the container role of related data and logic. Definition class Syntax: class ClassName (base_class [es]): "optional documentation string" static_member_declarations method_declarations define a class using the class keyword. You can provide an optional parent class or base class. If no base class is available, object is used as the base class by default. The class line is followed by optional document strings, static member definitions, and method definitions. '''Class calculatorClass (object): ''' first class: calculatorClass ''' # defines a static variable to save the current version = 1.0 # sets the input parameter and assigns the def _ init _ (self, one = 10, two = 20): self. first = one self. second = two ''' 'add''' def add (self): return self. first + self. second ''' subtraction, take the positive number ''' def sub (self): if self. first> self. second: return (self. first-self.second) else: return (self. second-self.first) ''' multiplication ''' def mul (self): return sel F. first * self. second ''' division ''' def div (self): if self. second! = 0: return self. first/self. second else: pass ''' modulo ''' def mod (self): if self. second! = 0: return self. first % self. second else: pass ''' the above class creates a static variable version, and the Use Case saves the version information. _ Init _ () is a special method that is automatically executed when a class instance is created. This method can be used as a build function, but it does not create an instance. It is only the first method executed after the object is created. It aims to execute some necessary initialization work for this object. ''' Create a computer instance ''' cal = calculatorClass (5, 2, call The method and attribute '''print "The current version:", cal. versionprint "----------------------------------" print "The two number add:", cal. add () print "The two number sub:", cal. sub () print "The two number mul:", cal. mul () print "The two number div:", cal. div () print "The two number mod:", cal. mod ()
The running result is as follows: