官术网_书友最值得收藏!

Classes and object programming

Classes are a way to create new kinds of objects and they are central to object-oriented programming. A class defines a set of attributes that are shared across instances of that class. Typically, classes are sets of functions, variables, and properties.

The object-oriented paradigm is compelling because it gives us a concrete way to think about and represent the core functionality of our programs. By organizing our programs around objects and data rather than actions and logic, we have a robust and flexible way to build complex applications. The actions and logic are still present of course, but by embodying them in objects, we have a way to encapsulate functionality, allowing objects to change in very specific ways. This makes our code less error-prone, easier to extend and maintain, and able to model real-world objects.

Classes are created in Python using the class statement. This defines a set of shared attributes associated with a collection of class instances. A class usually consists of a number of methods, class variables, and computed properties. It is important to understand that defining a class does not, by itself, create any instances of that class. To create an instance, a variable must be assigned to a class. The class body consists of a series of statements that execute during the class definition. The functions defined inside a class are called instance methods. They apply some operations to the class instance by passing an instance of that class as the first argument. This argument is called self by convention, but it can be any legal identifier. Here is a simple example:

    class Employee(object): 
numEmployee = 0
def __init__(self, name, rate):
self.owed = 0
self.name = name
self.rate=rate
Employee.numEmployee += 1

def __del__(self):
Employee.numEmployee -= 1

def hours(self, numHours):
self.owed += numHours * self.rate
return("%.2f hours worked" % numHours)

def pay(self):
self.owed = 0
return("payed %s " % self.name)

Class variables, such as numEmployee, share values among all the instances of the class. In this example, numEmployee is used to count the number of employee instances. Note that the Employee class implements the __init__ and __del__ special methods, which we will discuss in the next section.

We can create instances of the Employee objects, run methods, and return class and instance variables by doing the following:

主站蜘蛛池模板: 大洼县| 昌平区| 灵石县| 鄯善县| 凤城市| 清流县| 盱眙县| 招远市| 鱼台县| 奇台县| 丰宁| 内丘县| 历史| 海晏县| 璧山县| 达州市| 抚州市| 唐海县| 岚皋县| 衡阳县| 桦川县| 疏附县| 桃源县| 鸡泽县| 阳朔县| 玛纳斯县| 龙陵县| 舟山市| 曲松县| 右玉县| 富民县| 密山市| 阳春市| 平和县| 望城县| 尼木县| 裕民县| 怀柔区| 衡水市| 新绛县| 开阳县|