Python System Study Notes (10) --- class

Source: Internet
Author: User

Methods of the self class have only one special difference from common functions -- they must have an additional first parameter name, but you do not assign a value to this parameter when calling this method, python provides this value. This special variable refers to the object itself, which is named self by convention. Although you can give this parameter any name, it is strongly recommended that you use the self name-other names are not in favor of you. The self in Python is equivalent to the self pointer in C ++ and the this reference in Java and C. You must be wondering how Python assigns values to self and why you don't need to assign values to it. This can be clarified by an example. Assume that you have a class named MyClass and an instance named MyObject of this class. When you call this object method MyObject. method (arg1, arg2), this will be automatically converted from Python to MyClass. method (MyObject, arg1, arg2) -- this is the principle of self. This also means that if you have a method that does not require a parameter, you still have to define a self parameter for this method. Class objects support two types of operations: Property Reference and instantiation. Attribute reference uses the same standard syntax as all attribute references in Python: obj. name. After a class object is created, all the names in the class namespace are valid attribute names. So if the class is defined as follows: class MyClass: "A simple example class" I = 12345 def f (self): return 'Hello world', then MyClass. I and MyClass. f is a valid Property Reference and returns an integer and a method object respectively. You can also assign values to class attributes. You can assign values to MyClass. I to modify the attributes. _ Doc _ is also A valid attribute. The document string of the returned class is "A simple example class ". Class instantiation uses function symbols. You only need to regard the class object as a non-parameter function that returns the new class instance. For example (assuming the previous class is used): x = MyClass () creates a new class instance and assigns the object to the local variable x. This instantiation operation ("call" a Class Object) creates an empty object. Many classes tend to create objects in the initial state. Therefore, the class may define a special method named _ init _ (), as shown below: def _ init _ (self): self. if data = [] class defines the _ init _ () method, the class instantiation operation automatically calls the _ init _ () method for the newly created class instance. So in the following example, you can create a new instance like this: x = MyClass (). Of course, for the sake of elasticity, the _ init _ () method can have parameters. In fact, the parameter is passed to the class instantiation operation through _ init. The _ init _ method has many special meanings in the Python class. Now we will learn the meaning of the _ init _ method. The _ init _ method runs immediately when an object of the class is created. This method can be used to initialize your object. Note that the start and end of the name are double underscores. Use the _ init _ method [python] class SayHello: def _ init _ (self, hellostr): self. data = hellostr def sayHi (self, histr): print 'Hi' x = SayHello ("hello world") print '% s' % (x. data) x. sayHi ('Hi') is called a data attribute. This is equivalent to "instance variable" in Smalltalk or "data member" in C ++ ". Like local variables, data attributes do not need to be declared. They will generate self when used for the first time. data is the second method of data properties. Generally, the method is directly called: x. sayHi ('Hi') in our example, this will return the string 'hi '. Inheritance of course, if a language does not support inheritance, "class" makes no sense. The definition of a derived class is as follows: class DerivedClassName (BaseClassName):... the name of BaseClassName (the base class name in the example) must be in the same scope as that of the derived class. In addition to classes, expressions can also be used. This is very useful when the base class is defined in another module: class DerivedClassName (modname. BaseClassName): the execution process defined by the derived class is the same as that defined by the base class. When constructing a derived class object, you remember the base class. This is especially useful when parsing attribute references: If the Requested attribute cannot be found in the class, you can search for the base class. If the base class is derived from another class, this rule will be applied recursively. The instantiation of a derived class has nothing special: DerivedClassName () (derived class in the display column) creates a new class instance. Method reference is parsed according to the following rules: Search for the corresponding class attributes. If necessary, search by level along the base class chain. If the function object is found, this method reference is legal. A derived class may overwrite the method of its base class. Because the method does not have the privilege to call other methods in the same object, when the method of the base class calls the method of the same base class, it may actually call the override method in the derived class. (For C ++ programmers, all methods in Python are essentially virtual methods .) The override method in a derived class may be an extension rather than a simple replacement of the cognominal method in the base class. There is a simple method that can directly call the base class method, as long as it is called: "BaseClassName. methodname (self, arguments )". Sometimes this is useful to customers. (Note that only the base class can be used in the same global scope definition or import .) [Python] #! /Usr/bin/python # Filename: inherit. py class SchoolMember: ''' Represents any school member. '''def _ init _ (self, name, age): self. name = name self. age = age print '(Initialized SchoolMember: % s)' % self. name def tell (self): ''' Tell my details. '''print 'name: "% s" Age: "% s" '% (self. name, self. age), class Teacher (SchoolMember): ''' Represents a teacher. '''def _ init _ (self, name, age, salary ): SchoolMember. _ init _ (self, name, age) self. salary = salary print '(Initialized Teacher: % s)' % self. name def tell (self): SchoolMember. tell (self) print 'salary: "% d" '% self. salary class Student (SchoolMember): ''' Represents a student. '''def _ init _ (self, name, age, marks): SchoolMember. _ init _ (self, name, age) self. marks = marks print '(Initialized Student: % s)' % self. name def tell (self ): SchoolMember. tell (self) print 'Marks: "% d" '% self. marks t = Teacher ('Mrs. shrividya', 40,300 00) s = Student ('swaroop ', 22, 75) print # prints a blank line members = [t, s] for member in members: member. tell () # works for both Teachers and Students 4. Key Concepts of Operator Overloading * Operator Overloading blocks regular Python operations. * Class can overload all Python expression operations. * Supports heavy-load printing, function calling, and vertex number operations. * Overload makes the behavior of a class instance look like a built-in type. * Overloading is implemented by providing class methods with special names. If a class provides methods with some special names, Python will automatically call these methods when the class instance appears in an operation-related expression. 1. Common operators overload methods and methods overload call _ init _ constructor method object creation: X = Class () _ del _ destructor method object reclaim _ add _ operator + X + Y, X + = Y _ sub _ operator-X-Y, x-= Y _ or _ operator | (bit OR) X | y x | = Y _ repr __,__ str _ print, convert print X [_ str _], repr (X), str (X) _ call _ function call X () _ getattr _ vertex number operation X. undefined _ setattr _ attribute value assignment statement X. any = Value _ getitem _ index Operation X [key], the for loop without _ iter _ and other iterator _ setitem _ Index Assignment Statement X [key] = value _ len _ length len (X ), true Value Test _ cmp _ comparison X = Y, X _ lt _ specific comparison X <Y (or e Lse _ cmp _) _ eq _ specific comparison X = Y (or else _ cmp __) _ radd _ Addition on the left + Noninstance + X _ iadd _ Addition on the ground (enhanced) X + = Y (or else _ add __) _ iter _ the iteration environment is used for loop, test, list, ing, and names of all other overloaded methods. There are two underline characters before and after the names to distinguish the variable names defined in the same type. The ing between special method names and expressions or operations is pre-defined by the Python language. All methods that overload operators are optional: if a method is not written, the defined class does not support this operation. Most overload methods are only used in advanced programs that require object behavior to behave like built-in functions. However, the __init _ constructor usually appears in most classes. _ Getitem _ intercept index computation _ getitem _ intercept instance index operations. When instance X is indexed like X [I], Python calls the _ getitem _ method inherited by this instance. (If any), pass X as the first parameter, and pass the index value in brackets to the second parameter python to implement Singleton mode [python] #! /Usr/bin/env python #-*-coding: UTF-8-*-import OS class IOLoop (object): @ classmethod def instance (self): if not hasattr (self, "_ instance"): self. _ instance = self () return self. _ instance @ classmethod def initialized (self): "Returns true if the singleton instance has been created. "" return hasattr (self, "_ instance") def service (self): print 'hello, world' print IOLoop. initialized () ioloop = IOLoop. instance () ioloop. service () # if OS. fork () = 0: print IOLoop. initialized () ioloop = IOLoop. instance () ioloop. service () exercise question writing a class inherits a base class [python] # Creating a class hierarchy with an abstract base class. class Employee: "Abstract base class Employee" def _ init _ (self, first, last): "" Employee constructor, takes first name and last name. NOTE: Cannot create object of class Employee. "if self. _ class _ = Employee: raise NotImplementedError, "Cannot create object of class Employee" self. firstName = first self. lastName = last def _ str _ (self): "String representation of Employee" return "% s" % (self. firstName, self. lastName) def _ checkPositive (self, value): "Utility method to ensure a value is positive" if value <0: raise ValueError, "Attribute value (% s) must be positive "% value else: return value def earnings (self):" "Abstract method; derived classes must override" raise NotImplementedError, "Cannot call abstract method" class Boss (Employee): "" Boss class, inherits from Employee "def _ init _ (self, first, last, salary ): "Boss constructor, takes first and last names and salary" Employee. _ init _ (self, first, last) self. weeklySalary = self. _ checkPositive (float (salary) def earnings (self): "" Compute the Boss's pay "return self. weeklySalary def _ str _ (self): "String representation of Boss" return "% 17 s: % s" % ("Boss", Employee. _ str _ (self) class CommissionWorker (Employee): "CommissionWorker class, inherits from Employee" def _ init _ (self, first, last, salary, commission, quantity): "CommissionWorker constructor, takes first and last names, salary, commission and quantity" Employee. _ init _ (self, first, last) self. salary = self. _ checkPositive (float (salary) self. commission = self. _ checkPositive (float (commission) self. quantity = self. _ checkPositive (quantity) def earnings (self): "Compute the CommissionWorker's pay" return self. salary + self. commission * self. quantity def _ str _ (self): "String representation of CommissionWorker" "return" % 17 s: % s "% (" Commission Worker ", Employee. _ str _ (self) class PieceWorker (Employee): "PieceWorker class, inherits from Employee" def _ init _ (self, first, last, wage, quantity): "PieceWorker constructor, takes first and last names, wage per piece and quantity" Employee. _ init _ (self, first, last) self. wagePerPiece = self. _ checkPositive (float (wage) self. quantity = self. _ checkPositive (quantity) def earnings (self): "Compute PieceWorker's pay" return self. quantity * self. wagePerPiece def _ str _ (self): "String representation of PieceWorker" "return" % 17 s: % s "% (" Piece Worker ", Employee. _ str _ (self) class HourlyWorker (Employee): "HourlyWorker class, inherits from Employee" def _ init _ (self, first, last, wage, hours): "" HourlyWorker constructor, takes first and last names, wage per hour and hours worked "Employee. _ init _ (self, first, last) self. wage = self. _ checkPositive (float (wage) self. hours = self. _ checkPositive (float (hours) def earnings (self): "" Compute HourlyWorker's pay "if self. hours <= 40: return self. wage * self. hours else: return 40 * self. wage + (self. hours-40) * self. wage * 1.5 def _ str _ (self): "String representation of HourlyWorker" "return" % 17 s: % s "% (" Hourly Worker ", employee. _ str _ (self) # main program # create list of Employees www.2cto. comemployees = [Boss ("John", "Smith", 800.00), CommissionWorker ("Sue", "Jones", 200.0, 3.0, 150), PieceWorker ("Bob ", "Lewis", 2.5, 200), HourlyWorker ("Karen", "Price", 13.75, 40)] # print Employee and compute earnings for employee in employees: print "% s earned $ %. 2f "% (employee, employee. earnings ())

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.