Use [those things] Python classes in python

Reference Source

https://www.runoob.com/python/python-object.html

Meaning some of the terms

  1. Class (Class): used to describe a collection of objects having the same properties and methods. It defines each object in the collection are commonAttributeswithmethod. Objects are instances of classes.
  2. Class variables: Class variables are common throughout the instantiated object. And class variables defined outside the body of the function in the class. Class variables are typically not used as instance variables.(Each instance shared)
  3. Examples of variables: the class declaration, the attribute variable is represented. This variable is called an instance variable, but the statement is in addition to other members of the class methods inside the class declaration.(Each instance individually)
  4. Data members: class variables or instance variables, for the associated data processing and class instance object.
  5. Method: function defined in the class.
  6. Instantiate: create an instance of a class, the specific object class.
  7. Object: a data structure example defined by the class. Objects include two data members (instance variables and class variables) and methods.
  8. Local variables: variables defined in the process, only the role of the current instance of the class.
  9. Method overrides: If you can not meet the needs of the subclass inherits from a parent class, can be rewritten, this process is called covering methods (override), also known as the overriding method.
  10. Inheritance: that is, a derived class (derived class) inherits the base class (base class) fields and methods. Inheritance also allows a derived class object as a base class object treated. For example, there is such a design: the object type is derived from a Dog Animal class, which is an analog "Is a (is-a)"Relationship (FIG embodiment, Dog is an Animal).

Create a python class

class ClassName:
	'类文档字符串'
	类体

String class documentation can be viewed through the following command:

ClassName.__doc__

Class is composed ofClass MembersmethodProperty datacomposition

for example:

# -*- 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 %d" % Employee.empCount)
 
   def displayEmployee(self):
      print("Name : ", self.name,  ", Salary: ", self.salary)
  1. empCount variable is aClass variablesIts value will be shared between all instances of this class. You canInner classesorExternal classUse Employee.empCount access.
  2. A first method __init __ () method is a special method is called a constructor or class initializer,When an instance of this class will call the method created
  3. Examples of representatives of the class of self,When self-defined methods must be some kind ofWhen calling does not have to pass the appropriate parameters. Method in class only one specific difference from ordinary functions - they must have an extra first parameter name, as is customary its name is self.
  4. What is the inner class, outside of class what is
    the definition of class is an inner class in other classes, inner classes outside layer is the outer class.

python create an instance of an object

Examples of a similar class function call in the python, the name of the class Employee used to instantiate and receives parameters __init__ method.

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

Access Properties

python use the dot. attribute access to the class

Complete example:

# -*- 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 %d" % Employee.empCount)
 
   def displayEmployee(self):
      print("Name : ", self.name,  ", Salary: ", self.salary)
 
//创建 Employee 类的第一个对象
emp1 = Employee("Zara", 2000)
//创建 Employee 类的第二个对象
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)

Program results are as follows:

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

You can also add, modify, delete class attributes:

# -*- 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 %d" % Employee.empCount)
 
   def displayEmployee(self):
      print("Name : ", self.name,  ", Salary: ", self.salary)
 
//创建 Employee 类的第一个对象
emp1 = Employee("Zara", 2000)
//创建 Employee 类的第二个对象
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)

emp1.age = 7
//给对象emp1添加属性age,赋值为7
print(emp1.age)
emp1.age = 8
//更改对象emp1属性age为8
print(emp1.age)
del emp1.age
//删除对象emp1属性age

if hasattr(emp1, 'age') is True:
//hasatter(obj, name) 检查对象obj是否存在一个属性name,存在则返回True
        print(getattr(emp1, 'age'))
        //getattr(obj, name)返回对象obj中属性name的值,如果属性name不存在则报错
else:
        print("No")
setattr(emp1, 'age', 8)
//setattr(obj,name,value) : 设置一个属性name为值value。如果属性不存在,会创建一个新属性。
if hasattr(emp1, 'age') is True:
        print(getattr(emp1, 'age'))
else:
        print("No")
if hasattr(emp2, 'age') is True:
        print(getattr(emp2, 'age'))
else:
        print("No")

delattr(emp1, 'age')
//delattr(obj, name) : 删除属性name,若属性不存在则报错

Program results are as follows:

Name : Zara , Salary: 2000
Name : Manni , Salary: 5000
Total Employee 2
7
8
No
8
No

Visible to add properties in an object, and did not affect another object.

python built-in class attribute

__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
__bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)

python object is destroyed (garbage collection)

python using reference counting this simple technology to track and recover waste. How many references to the use of all the objects inside each python recorded. An internal tracking variables, called a reference counter.
whenObjectsWhen it is created,It creates a reference countWhen thisObjectsWhen no longer needed, that is to say, thisObjectsofReference count becomes 0When it is garbage collected. But the recovery is not "immediately" by the interpreter at the appropriate time, willGarbage objectsOccupiedMemory spaceRecycling.

Class inheritance

The main benefit of object-oriented programming is to bring oneCode reuseOne way to achieve this is through the inheritance mechanism reuse.
Create a new class by inheriting is calledSubclassorDerived class, Inherited class calledBase classfatherorSuperclass

In python inherits some of the features:

  1. Call the parent class constructor if desired parent class constructor in subclass needs to be displayed or not override the parent class constructor .
  2. inWhen the base class callsWe need to add class name prefix base classesAnd the need to bring the self argument variables. The difference is thatWhen using an ordinary function classandParameter does not need to take self
  3. python always first find the corresponding type of method, corresponding method if it can not find in a derived class, it began to look one by one to the base class. (First find method call in this class, the base class can not be found before going to look for).

for example:

# -*- coding: UTF-8 -*-
 
class Parent:        
//定义父类
   parentAttr = 100
   def __init__(self):
      print("调用父类构造函数")
 
   def parentMethod(self):
      print('调用父类方法')
 
   def setAttr(self, attr):
      Parent.parentAttr = attr
 
   def getAttr(self):
      print("父类属性 :", Parent.parentAttr)
 
class Child(Parent): 
//定义子类
   def __init__(self):
      print("调用子类构造方法")
 
   def childMethod(self):
      print('调用子类方法')
 
c = Child()          
//实例化子类
c.childMethod()      
//调用子类的方法
c.parentMethod()     
//调用父类方法
c.setAttr(200)       
//再次调用父类的方法 - 设置属性值
c.getAttr()          
//再次调用父类的方法 - 获取属性值

Program results are as follows:

Subclass constructor method call
to call sub-class method
calls the method of the parent class
the parent class attributes: 200

python a plurality of subclasses inherit parent class may also

class A:        
//定义类 A
.....

class B:         
//定义类 B
.....

class C(A, B):   
//继承类 A 和 B
.....

python subclass inherits the parent class constructor Description

If desired parent class constructor in subclass requiresCall the parent class constructor explicitly,orNot override the parent class constructor.
Subclass does not override _ the init _, subclasses instance, will automatically call the parent class definition _ the init .
If you override the
init time _ instance subclasses, it will not call the parent class has defined _ init _.

If rewrite _ the init time _ to inherit the parent class constructor, you can usesuper Keyword

super (subclass, Self) ._ the init _ (parameter 1, parameter 2, ...)

or

Class Name Parent ._ the init _ (Self, parameter 1, parameter 2, ...)

class Father(object):
    def __init__(self, name):
        self.name=name
        print ( "name: %s" %( self.name))
    def getName(self):
        return 'Father ' + self.name
 
class Son(Father):
    def __init__(self, name):
        super(Son, self).__init__(name)
        print ("hi")
        self.name =  name
    def getName(self):
        return 'Son '+self.name
 
if __name__=='__main__':
    son=Son('runoob')
    print ( son.getName() )

or

class Father(object):
    def __init__(self, name):
        self.name=name
        print ( "name: %s" %( self.name))
    def getName(self):
        return 'Father ' + self.name
 
class Son(Father):
    def __init__(self, name):
        Father.__init__(self, name)
        print ("hi")
        self.name =  name
    def getName(self):
        return 'Son '+self.name
 
if __name__=='__main__':
    son=Son('runoob')
    print ( son.getName() )

Method overrides

If your parent class method function can not meet your needs, you can override the parent class method in your subclass
simply, it is that we can define a method and a parent class with the same name in the subclass, so call this when the method used is redefined subclass, not the parent class.

Basis overloaded methods

What is overloaded functions:
overloaded function is a special case of a function, for ease of use, python allowed to declare several functions in the same range similarFunction of the same nameBut these functions with the same nameFormal parameters(Refer to the number of parameters, the type or order) to bedifferent, That isPerform different functions with the same function. This is overloaded functions. Overloaded function used to implement the functions and the like are different types of data processing problems.Not only function return values ​​of different types

Class attributes and methods

  1. Class private property
    __private_attrs:Two start with an underscoreStating that the property isprivateOr it can not be used directly to access from outside the class. self .__ private_attrs method as used in the interior of the class.
  2. Method class
    within the class, the def keyword can be defined as a class method, and is generally different function definitions, methods must include the class parameter self, and as the first parameter
  3. Private class methods
    __private_method: two begins with an underscore, the method is declared as a private method can not be called outside the class. Calls self .__ private_methods within the class

Single underline, double underline, double underline head and tail description:

  1. _ Foo _: a special method is defined, system-defined names generally similar _ the init _ () or the like.
  2. _foo: to indicate the single leading underscore is protected types of variables, namely the protection type can only allow it to itself and the subclass access,It can not be used from module import *
  3. __foo: double underline indicates the type of private (private) variables can only be allowed to visit the class itself.

Epilogue

If you have amendments or questions, please leave a message or contact me by mail.
Hand very hard, if my article helpful to you, please indicate the source.

Guess you like

Origin blog.csdn.net/Zhang_Chen_/article/details/93311916