Python - 类/对象

Python - 类/对象 首页 / Python2入门教程 / Python - 类/对象

如果您以前没有使用面向对象(OO)编程的经验,则可能需要查阅有关它的入门课程或至少某种形式的教程,以便掌握基本概念。

创建类

class 语句创建一个新的类定义。该类的名称紧随关键字 class 后跟冒号,如下所示-

class ClassName:
   'Optional class documentation string'
   class_suite
  • 该类有一个文档字符串,可以通过 ClassName .__ doc __ 访问。

    无涯教程网

  • class_suite 由定义类成员,数据属性和函数的所有组件语句组成。

以下是一个简单的Python类的示例-

class Employee:
   'Common base class for all employees'
   empCount=0

   def __init__(self, name, salary):
      self.name=name
      self.salary=salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

创建实例对象

要创建类的,请使用类名称调用该类,然后传递其 __ init __ 方法接受的任何参数。

"This would create first object of Employee class"
emp1=Employee("Learnfk", 2000)
"This would create second object of Employee class"
emp2=Employee("Manni", 5000)

访问类属性

您可以使用带点运算符和对象来访问对象的属性。将使用类名称访问类变量,如下所示:

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

现在,将所有概念放在一起-

#!/usr/bin/python

class Employee:
   'Common base class for all employees'
   empCount=0

   def __init__(self, name, salary):
      self.name=name
      self.salary=salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

"This would create first object of Employee class"
emp1=Employee("Learnfk", 2000)
"This would create second object of Employee class"
emp2=Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

执行以上代码后,将产生以下输出-

Name :  Learnfk ,Salary:  2000
Name :  Manni ,Salary:  5000
Total Employee 2

您可以随时添加,删除或修改类和对象的属性-

emp1.age=7  # 添加“age”属性。
emp1.age=8  # 修改“age”属性。
del emp1.age  # 删除“age”属性。

除了使用普通语句访问属性外,还可以使用以下功能-

  • getattr(obj,name [,default])   - 访问对象的属性。

  • hasattr(obj,name)                       -  检查属性是否存在。

  • setattr(obj,name,value)          -   设置属性。如果属性不存在,则将创建它。

  • delattr(obj,name)                        -   删除属性。

hasattr(emp1, 'age')    # 如果存在“age”属性,则返回True
getattr(emp1, 'age')    # 返回“age”属性的值
setattr(emp1, 'age', 8) # 在8中设置属性“age”
delattr(empl, 'age')    # 删除属性“age”

内置属性

每个Python类都遵循以下内置属性,并且可以像其他任何属性一样使用点运算符来访问它们-

  • __ dict __          - 包含类名称空间的字典。

  • __ doc __          - 类文档字符串,如果未定义,则为无。

  • __ name __      - 类名。

  • __ module __   - 定义类的模块名称。在交互模式下,此属性为" __main__"。

  • __ bases __       - 包含基类的可能为空的元组,按基类在基类列表中的出现顺序排列。

对于上面的类,让无涯教程尝试访问所有这些属性-

#!/usr/bin/python

class Employee:
   'Common base class for all employees'
   empCount=0

   def __init__(self, name, salary):
      self.name=name
      self.salary=salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

执行以上代码后,将产生以下输出-

Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2, 
'displayEmployee': <function displayEmployee at 0xb7c8441c>, 
'__doc__': 'Common base class for all employees', 
'__init__': <function __init__ at 0xb7c846bc>}

销毁对象

Python会自动删除不需要的对象以释放内存空间。 Python定期回收不再使用的内存块的过程称为垃圾收集。

链接:https://www.learnfk.comhttps://www.learnfk.com/python/python-classes-objects.html

来源:LearnFk无涯教程网

Python的垃圾回收器在程序执行期间运行,并在对象的引用计数达到零时触发。对象的引用计数随指向它的别名数量的变化而变化。

当为对象分配新名称或将其放置在容器(列表,元组或字典)中时,其引用计数就会增加。当使用 del 删除对象,重新分配其引用或引用超出范围时,该对象的引用计数会减少。当对象的引用计数达到零时,Python会自动收集它。

a=40      # Create object <40>
b=a       # Increase ref. count  of <40> 
c=[b]     # Increase ref. count  of <40> 

del a       # Decrease ref. count  of <40>
b=100     # Decrease ref. count  of <40> 
c[0]=-1   # Decrease ref. count  of <40> 

通常,您不会注意到垃圾收集器何时销毁一个孤立并回收其空间。但是,一个类可以实现称为析构函数的特殊方法 __ del __(),该方法将在即将被销毁时调用。此方法可能用于清除使用的任何非内存资源。

这个__del __()析构函数输出将要销毁的的类名-

#!/usr/bin/python

class Point:
   def __init__( self, x=0, y=0):
      self.x=x
      self.y=y
   def __del__(self):
      class_name=self.__class__.__name__
      print class_name, "destroyed"

pt1=Point()
pt2=pt1
pt3=pt1
print id(pt1), id(pt2), id(pt3) # 打印obejcts的ID
del pt1
del pt2
del pt3

执行以上代码后,将产生以下输出-

3083401324 3083401324 3083401324
Point destroyed

注意-理想情况下,您应该在单独的文件中定义类,然后使用 import 语句将其导入主程序文件中。

继承

子类继承其父类的属性,您可以在子类中使用父类的这些属性。子类也可以覆盖父类的数据成员和方法。

子类的声明与父类很相似;但是,在类名称后给出了要继承的父类列表-

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite
#!/usr/bin/python

class Parent:        # define parent class
   parentAttr=100
   def __init__(self):
      print "Calling parent constructor"

   def parentMethod(self):
      print 'Calling parent method'

   def setAttr(self, attr):
      Parent.parentAttr=attr

   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class
   def __init__(self):
      print "Calling child constructor"

   def childMethod(self):
      print 'Calling child method'

c=Child()            # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method

执行以上代码后,将产生以下输出-

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

类似地,您可以从多个父类驱动一个类,如下所示:

class A:        # define your class A
.....

class B:         # define your class B
.....

class C(A, B):   # subclass of A and B
.....

您可以使用issubclass()或isinstance()函数来检查两个类和之间的关系。

方法覆盖

您可以覆盖父类方法。覆盖父级方法的原因之一是因为父类的方法实现满足不了你当前的需求。

#!/usr/bin/python

class Parent:        # define parent class
   def myMethod(self):
      print 'Calling parent method'

class Child(Parent): # define child class
   def myMethod(self):
      print 'Calling child method'

c=Child()          # instance of child
c.myMethod()         # child calls overridden method

执行以上代码后,将产生以下输出-

Calling child method

下表列出了一些通用功能,您可以在自己的类中覆盖它们-

Sr.No.Method, 描述 & Sample Call
1

__ init__(self [,args ...])

构造函数(带有任何可选参数)

用例: obj=className(args)

2

__del__(self)

析构函数,删除一个对象

示例:del obj

3

__ repr __(self)

可判断的字符串表示形式

示例: repr(obj)

4

__ str __(self)

可打印的字符串表示

示范: str(obj)

5

__ cmp__(self,x)

对象比较

示例: cmp(obj,x)

重载运算符

您可以在类中定义 __ add __ 方法以执行矢量加法,然后plus运算符将按照预期的方式工作-

#!/usr/bin/python

class Vector:
   def __init__(self, a, b):
      self.a=a
      self.b=b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1=Vector(2,10)
v2=Vector(5,-2)
print v1 + v2

执行以上代码后,将产生以下输出-

Vector(7,8)

数据隐藏

在类定义之外,对象的属性可能不可见。您需要使用双下划线前缀来命名属性,这样外部人就无法直接看到这些属性。

#!/usr/bin/python

class JustCounter:
   __secretCount=0
  
   def count(self):
      self.__secretCount += 1
      print self.__secretCount

counter=JustCounter()
counter.count()
counter.count()
print counter.__secretCount

执行以上代码后,将产生以下输出-

1
2
Traceback (most recent call last):
   File "test.py", line 12, in <module>
      print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'

Python通过内部更改名称以包括类名称来保护这些成员。您可以访问 object._className__attrName 这样的属性。

.........................
print counter._JustCounter__secretCount

执行以上代码后,将产生以下输出-

1
2
2

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

零基础学Python -〔尹会生〕

如何设计一个秒杀系统 -〔许令波〕

深入浅出计算机组成原理 -〔徐文浩〕

说透敏捷 -〔宋宁〕

手把手带你写一个Web框架 -〔叶剑峰〕

自动化测试高手课 -〔柳胜〕

程序员职业规划手册 -〔雪梅〕

给程序员的写作课 -〔高磊〕

好记忆不如烂笔头。留下您的足迹吧 :)