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

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:

主站蜘蛛池模板: 隆化县| 普定县| 新密市| 杭州市| 安远县| 林甸县| 大厂| 尉犁县| 洪江市| 南丹县| 黔江区| 南川市| 敦煌市| 甘谷县| 达州市| 克拉玛依市| 芦山县| 黑山县| 吉木乃县| 陆良县| 泊头市| 邻水| 封开县| 抚顺县| 罗田县| 咸丰县| 白城市| 苗栗县| 海淀区| 维西| 义马市| 塔城市| 寿光市| 瓮安县| 宁夏| 恩平市| 金平| 柞水县| 台南市| 瓮安县| 阳西县|