Python 类

1.类的创建  

  (1)使用class语句来创建一个新类,class之后为类的名称并以冒号结尾:

class <类名>:
 <语句>

  以下是一个简单的实例:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

class Employee:
   '所有员工的基类'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1

   def displayCount(self):
     print('Total Employee %s' % Employee.empCount)

   def displayEmployee(self):
      print('Name : ', self.name,  ', Salary: ', self.salary)
  • empCount变量是一个类变量,它的值将在这个类的所有实例之间共享。你可以在内部类或外部类使用Employee.empCount访问。
  • 第一种方法__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法

  (2)创建实例对象

"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)
"创建 Employee 类的第二个对象"
emp2 = Employee("Manni", 5000)

  (3)访问属性

emp1.displayEmployee()
emp2.displayEmployee()
print('Total Employee %d' % Employee.empCount)

2.类的方法

  在一个类中,可能出现三种方法。普通方法,静态方法和类方法。、

  (1)普通方法第一个参数必须是 self.普通方法只能通过类创建的对象调用,这时 self就代表这个对象本身,通过self可以直接访问对象的属性。

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

class Student(object):

    count = 0
    books = []
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def printInstanceInfo(self):
        print('%s is %d years old' %(self.name, self.age))


wilber = Student("Wilber", 28)
wilber.printInstanceInfo()

  (2)静态方法没有参数的限制,既不需要实例参数,也不需要类参数。定义的时候使用 @staticmethod。静态方法可以通过类名访问,也可以通过实例对象访问。

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-


class Student(object):

    count = 0
    books = 'python'
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def printClassAttr():
        print(Student.count)
        print(Student.books)
    pass

Student.printClassAttr()
wilber = Student("Wilber", 28)
wilber.printClassAttr()

  (3)类方法以cls作为第一个参数,cls表示类本身,定义时使用@classmethod

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-


class Student(object):

    count = 0
    books = 'python'
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def printClassInfo(cls):
        print(cls)

Student.printClassInfo()
wilber = Student("Wilber", 28)
wilber.printClassInfo()

3.类的继承

  (1)单继承

class <类名>(父类名)
   <语句>

  如以下实例:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-


class F1:
    def __init__(self):
        self.name = 'yang'


class F2(F1):
    pass


obj = F2()
print(obj.name)

  以上代码运行后会输出 yang。

  (3)类的多继承

class 类名(父类1,父类2,....,父类n)
     <语句1>

  需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索,即方法在子类中未找到时,从左到右查找父类中是否包含方法

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

class F1:
    def __init__(self):
        self.name = 'yang'

class F2:
    def __init__(self):
        self.name = 'zheng'

class F3(F1,F2):
    pass

obj = F3()
print(obj.name)

  以上代码中,F3继承了F1和F2,在创建对象obj时,优先继承了F1中的__init__方法,因此输出 obj.name时显示的是 yang,如果将类F3的继承顺序改为 (F2,F1),输出的结果将会是 zheng.

  

 

posted @ 2016-07-02 10:58  yangyang1234.com  阅读(167)  评论(0编辑  收藏  举报