美文网首页
Python Note4 (OOP)

Python Note4 (OOP)

作者: qin7zhen | 来源:发表于2017-02-23 21:07 被阅读21次

Labels: Python, Class,Object

Ref:
Python Classes/Objects https://www.tutorialspoint.com/python/python_classes_objects.htm


Classes

  • Creating Class
    The name of the class immediately follows the keyword class followed by a colon as follow:
class ClassName:
   'Optional class documentation string'
   class_components

Example

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 displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

__attribute: Private attribute ('__'). Not be visible outside the class definition.

  • Creating instance objects
# This would create first object of Employee class
emp1 = Employee("Zara", 2000)
  • Accessing attributes and functions
emp1.displayEmployee()
print "Total Employee %d" % Employee1.empCount

object._className__attrName.: Access the private (hided) attributes.

  • Attributes accessing functions
Function Description
getattr(obj, name[, default]) access the attribute of object.
hasattr(obj,name) check if an attribute exists or not.
setattr(obj,name,value) set an attribute. If attribute does not exist, then it would be created.
delattr(obj, name) delete an attribute.

Examples:

hasattr(emp1, 'age')    # Returns true if 'age' attribute exists
getattr(emp1, 'age')    # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age')    # Delete attribute 'age'
  • Class Built-in Attributes
    It can be accessed using dot operator.
Attribute Description
__dict__ Dictionary containing the class's namespace.
__doc__ Class documentation string or none, if undefined.
__name__ Class name.
__module__ Module name in which the class is defined. This attribute is __main__ in interactive mode.
__bases__ A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

Example:

class Employee:
  'Common base class for all employees'
  empCount = 0
  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__

Result:

Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__',  'empCount': 2, 
'displayEmployee': <function displayEmployee at 0xb7c8441c>, 
'__doc__': 'Common base class for all employees'}
  • Class Inheritance
    The child class inherits the attributes of its parent class.
    A child class can also override data members and methods from the parent.
class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite

A class from multiple parent classes.

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

Check a relationships of two classes and instances:

  • issubclass(sub, sup) returns true if the given subclass sub is indeed a subclass of the superclass sup.

  • isinstance(obj, Class) returns true if obj is an instance of class Class or is an instance of a subclass of Class

  • Methods Overloading

  • Base Overloading Methods

Method Description Sample Call
__init__(self [,args...]) Constructor (with any optional arguments) obj = className(args)
__del__( self ) Destructor, deletes an object del obj
__repr__( self ) Evaluatable string representation repr(obj)
__str__( self ) Printable string representation str(obj)
__cmp__ ( self, x ) Object comparison cmp(obj, x)

相关文章

  • Python Note4 (OOP)

    Labels: Python, Class,Object Ref:Python Classes/Objects h...

  • Python OOP

    断断续续写了几年程序,终于接触到面向对象的编程方式。本文记录与以往编程体验不同的地方 数据和逻辑被封装: 1. 操...

  • Python OOP

    面向过程的程序设计把计算机程序视为一系列的命令集合,即一组函数的顺序执行。为了简化程序设计,面向过程把函数继续切分...

  • Python学习总结

    Python概述 数据类型 数据结构 OOP FP

  • python面向对象学习笔记-01

    学习笔记 # 0,OOP-Python面向对象 - Python的面向对象 - 面向对象编程 - 基础 -...

  • python面向对象程序设计(OOP)

    python面向对象程序设计(OOP) 类定义语法class className: 在python中可以...

  • 2018-04-14 开胃学习Python系列 - Object

    Python也是oop,虽然函数在Python生态系统中扮演重要角色。Python确实具有类别(classes) ...

  • python 类的细节

    下面我根据MARK Lutz的《Learning Python》中的“大师眼中的OOP”,列一些使用OOP的常见原...

  • 蓝天白云

    小米note4

  • python - OOP进阶

    前言 python的class有很多高级特性,除了OOP的三大特性,还在设计模式,自定制类和内存优化等都下了很多功...

网友评论

      本文标题:Python Note4 (OOP)

      本文链接:https://www.haomeiwen.com/subject/szmbwttx.html