Object-Oriented Programming in Python

Keywords: Python Attribute Programming Linux

Python Object-Oriented Programming

1 Overview

(1) Object-oriented programming

  Object-oriented programming is to use "class" and "object" to create various models to describe the real world. One reason for using object-oriented programming is that it can make the maintenance and expansion of programs simpler and greatly improve the efficiency of program development. In addition, object-oriented programs can make it easier for others to understand your code logic. In order to make team development more relaxed.

(2) Object-oriented features

   Class: A class is the abstraction, blueprint and prototype of a class of objects with the same attributes. The properties (data) and common methods of these objects are defined in the class.

   2) Object: An object is an instance of a class after instantiation. A class must be instantiated before it can be invoked in the program. A class can instantiate multiple objects. Each object can also have different attributes, just as human beings refer to all people, each person refers to specific objects. There are similarities and differences between people.

   3) Encapsulation: The assignment of data in a class and the internal call are transparent to external users, which makes the class a capsule or container containing data and methods of the class.

   4) Inheritance: A class can derive subclasses in which attributes and methods defined are automatically inherited by subclasses.

   5) Polymorphism: Polymorphism is an important feature of object-oriented. Simply put, "An interface, multiple implementations", refers to the derivation of different subclasses from a basic class, and each subclass inherits the same method name while implementing different methods of the parent class. This is the multiple forms of the same thing.

(3) Simple usage

class People(object):    #Create a class, capitalize the first letter of the class name, and inherit the object class
    def walk(self):
        print "i am walking..."
    def talk(self):
        print "talking with sb..."

p1 = People()   #Create an object that belongs to the People class
p1.walk()        #Call the walk method
p1.talk()

p2 = People()
p2.walk()
p2.talk()

Class 2 methods

(1) Methods and attributes of classes

   1) Method of Class-self

   Class methods (class functions) have only one special difference from normal functions - they must have an additional first parameter name, but when you call this method, you do not assign this parameter, and Python will provide it. This particular variable refers to the object itself, which is traditionally called self.

  If you have a class called MyClass and an instance of this class called MyObject. When you call the method MyObject.method(arg1, arg2) of this object, it will automatically change from Python to MyClass.method(MyObject, arg1, arg2)

   2)_init_() initialization

   Role: Initialization of entities

   For example: classDog:

      def__init__(self,name):

      self.DogName= name # must assign self, otherwise other functions in the class cannot be called

(3) Examples of class methods:

class People(object):
    info= 'test'  #Shared variables, if not found in instance variables, will find shared variables
    def __init__(self,name,age,job): #Constructor (instantiation function)
        self.name = name #To be an instance variable, that is, to change a local variable of a class into a global variable of a class
        self.age = age
        self.job = job
        #self.info = 't2'  #Change the value of info
    def walk(self):
        print "i am walking..."
    def talk(self):
        print "talking with sb...",People.info

p1 = People("Dayi",22,"it")
p2 = People("liuyi",24,"itman")
p3 = People("t3",18,"ll")

p1.info = "P1"
print 'P1:',p1.info
People.info = "haha"       #If the value of info is modified in the constructor, it cannot be modified here.
print 'p2:',p2.info
print 'p3:',p3.info

(4) Destructive function

  Automatically executed when instance is released or destroyed, it is usually used to do some finishing work, such as closing some database connections and closing temporary open files.

#!/usr/bin/env python
class Create_role:
    def __init__(self,name,age,job):
        self.name= name
        self.age =age
        self.job =job

    def show(self):
        print("Name:%s Age:%s Job:%s"%(self.name,self.age,self.job))

    def __del__(self):  #Define a destructive method
        print("%s It has been cleaned up thoroughly." %(self.name) )

r1 = Create_role("Dayi",18,"it")
print(r1.name)
r1.show()
del r1   #The destructor is executed immediately after the r1 call, and by default it will not execute until the program has completed execution.
r2 = Create_role("xiaoliu",23,"no")
r2.show()
r3 = Create_role("hehe",30,"bois")

(5) Private attributes and methods of classes (encapsulation of classes)

   Python's default membership functions and membership variables are public. To define a private variable in python, you just need to underline the name of the variable or function before the name of the variable or function, and then the function or variable will be private. Internally, after replacing membername with classname membername, when you use the name of the original private member externally, you will be prompted not to find it, but you can call it internally.

class People(object):
    info = 'test'  #Shared variables
    def __init__(self,name,age,job): #Constructor (instantiation function)
        self.name = name #To be an instance variable, that is, to change a local variable of a class into a global variable of a class
        self.__age = age  #Define a private property by prefixing the property name__
        self.job = job
        self.info = 't2'  #Change the value of info
        self.info_dic = {"name":'day',
                         "age":"33"}
    def get_info(self,info_type):
        if info_type == 'age':
            return self.__age
        elif info_type == 'job':
            return self.job
    def __breath(self):    #Define a private method that can only be invoked internally, and create a method that precedes the function name__
        print("%s is breathing..." %self.name)
    def walk(self):
        print "i am walking..."
        print(self.__breath())       #Invoking private methods internally
    def talk(self):
        print("talking with sb...",People.info)

p1 = People("Dayi",22,"it")
p2 = People("liuyi",24,"itman")

p1.walk()
print(p1.get_info("age"))
print(p1._People__age)   #Call read-only properties

Inheritance of Class 3

   Classes in Python can inherit parent class attributes or multiple parent classes at the same time; in the form of class class name (parent class 1, parent class 2), the child class can inherit all methods and attributes of the parent class, and can also overload the member functions and attributes of the parent class. It should be noted that if the member functions of the child class overload the parent class (i.e., the same name), the member functions of the child class will be used.

(1) Basic Inheritance of Classes

class SchoolMember(object):
    def __init__(self,name,age,sex): #Create a parent constructor
        self.name = name
        self.age = age
        self.sex = sex
    def tell(self):    #The parent class creates a method
        print('''--info of %s--
                name:%s
                age :%s
                sex :%s
        '''%(self.name,self.name,self.age,self.sex))

class Student(SchoolMember):    #Create a class and inherit SchoolMember
    def __init__(self,name,age,sex,grade):   #Create subclass inheritance functions
        SchoolMember.__init__(self,name,age,sex)   #Let the constructor of the subclass inherit the parent class
        self.grade = grade
    def pay_money(self):       #Create a method for subclasses
        print("---%s is paying the tuition fee---" % self.name)
    def tell(self):
        SchoolMember.tell(self)    #Let the tell() method of the subclass inherit the parent class
        print("---from %s" % self.grade)
class Teacher(SchoolMember):
    def __init__(self,name,age,sex,course,salary):
        SchoolMember.__init__(self,name,age,sex)
        self.course = course
        self.salary = salary
    def teaching(self):
        print("Teacher %s is teaching class of %s" %(self.name,self.course))

s = Student("dayi",33,"M","py s10")
t = Teacher("liu",18,"M","python", 60000)
s.tell()
t.tell()
s.pay_money()
t.teaching()

(2) Multiple Inheritance of Classes

   1) Inheritance 1:

class SchoolMember(object):
    def __init__(self,name,age,sex): #Create a parent constructor
        self.name = name
        self.age = age
        self.sex = sex
    def tell(self):    #The parent class creates a method
        print '''--info of %s--
                name:%s
                age :%s
                sex :%s
        '''%(self.name,self.name,self.age,self.sex)
class School(object):
    def __init__(self,name,addr,tel): #Create a parent constructor
        self.school_name = name
        self.addr = addr
        self.tel = tel
        self.stu_list = []
        self.tech_list = []
class Student(SchoolMember,School):    #Create a class and inherit School Member and Schol classes
    def __init__(self,name,age,sex,grade):   #Create subclass inheritance functions
        SchoolMember.__init__(self,name,age,sex)   #Let the constructor of the subclass inherit the parent class
        School.__init__(self,"beida","shahe",999) #Let the constructor of a subclass inherit the parent class and pass parameters
        self.grade = grade
    def pay_money(self):       #Create a method for subclasses
        print "---%s is paying the tuition fee---" % self.name
    def tell(self):
        SchoolMember.tell(self)    #Let the tell() method of the subclass inherit the parent class
        print '''---from school name :%s
                        class :%s
                        addr  :%s
        '''%(self.school_name,self.grade,self.addr)

s = Student("dayi",33,"M","py s10")
s.tell()
s.pay_money()

2) Inheritance II (through super):

class School(object):
    def __init__(self,name,addr):
        self.name= name
        self.addr= addr
        self.students =[]
        self.staffs=[]
    def enroll(self,stu_obj):
        print("For students%s Procedure for registration"%stu_obj.name )
        self.students.append(stu_obj)
    def hire(self,staff_obj):
        self.staffs.append(staff_obj)
        print("Employing new employees%s" % staff_obj.name)

class SchoolMember(object):
    def __init__(self,name,age,sex):
        self.name= name
        self.age =age
        self.sex =sex
    def tell(self):
        pass

class Teacher(SchoolMember):
    def __init__(self,name,age,sex,salary,course):
        super(Teacher,self).__init__(name,age,sex)
        self.salary= salary
        self.course= course
    def tell(self):
        print('''
        ---- info of Teacher:%s ----
        Name:%s
        Age:%s
        Sex:%s
        Salary:%s
        Course:%s
        '''%(self.name,self.name,self.age,self.sex,self.salary,self.course))

    def teach(self):
        print("%s is teaching course [%s]" %(self.name,self.course))

class Student(SchoolMember):
    def __init__(self,name,age,sex,stu_id,grade):
        super(Student,self).__init__(name,age,sex)
        self.stu_id= stu_id
        self.grade= grade
    def tell(self):
        print('''
        ---- info of Student:%s ----
        Name:%s
        Age:%s
        Sex:%s
        Stu_id:%s
        Grade:%s
        ''' % (self.name, self.name,self.age, self.sex, self.stu_id,self.grade))
    def pay_tuition(self,amount):
        print("%s has paid tution for $%s"% (self.name,amount) )


school = School("qinghua","Haidian")   #Create a class for the School object

t1 = Teacher("day",56,"MF",200000,"Linux")
t2 = Teacher("liu",22,"M",3000,"PythonDevOps")

s1 = Student("dayi123",36,"MF",1001,"PythonDevOps")
s2 = Student("hehe",19,"M",1002,"Linux")


t1.tell()    #Call tell() method of Teacher class
s1.tell()
school.hire(t1)
school.enroll(s1)
school.enroll(s2)

print(school.students)
print(school.staffs)
school.staffs[0].teach()#Get the first element in the staffs list and call the teach method in the Teacher class
#school.students[0].pay_tuition(2000) 

for stu in school.students:     #Loop the elements of the student list in the School class and assign them to stu
    stu.pay_tuition(5000)       #Call the pay_tuition() method in School and pass a parameter

(3) Succession summary

   py2 classical classes are inherited by depth first, while new classes are inherited by breadth first.

   Classic and new py3 classes are inherited by breadth first.

4. Polymorphism (one interface, multiple implementations):

  Polymorphism means that even if you don't know what type of object a variable is applied to, you can still manipulate it, and it also behaves differently depending on the type of object (or class).

class Animal:
    def __init__(self,name):  # Constructor of the class
        self.name= name

    def talk(self):  #Abstract method, defined by convention only
        pass #raiseNotImplementedError("Subclass must implement abstract method")

    @staticmethod
    def animal_talk(obj):   #Encapsulate the calling method in the parent class
        obj.talk()

class Cat(Animal):
    def talk(self):
        print('%s :Meow!'%self.name)

class Dog(Animal):
    def talk(self):
        print('%s: Woof! Woof!'%self.name)

d = Dog("I c")
#d.talk()

c = Cat("Kitten Cat")
#c.talk()
#
# def animal_talk(obj):
#     obj.talk()

Animal.animal_talk(c)    #Call c object
Animal.animal_talk(d)

5. Static Method and Class Method

(1) Static methods: Class static methods are nominally classified and managed. In fact, no attributes of classes or instances can be accessed in static methods. Static methods are loaded into static method-type objects when they are created. Static methods are created without self parameters and can be called directly by the class itself.

(2) Class methods: Class methods are loaded into classmethod-type objects when they are created. Class methods can be called directly by specific objects of the class, but class methods can only access class variables, not instance variables of the class.

(3) Attribute method: The attribute method of a class can change the method of a class into a static attribute of a class.

class MyClass(object):
    age = 22
    def __init__(self):
        self.name= "hehele"
    def sayhi(self):#You must instantiate to invoke
        print("---sayhi 1")
    @staticmethod
    def sayhi2():#Static methods, which have nothing to do with classes, can be called without instantiation, class Toolkit
        print("---sayhi 2")
    @staticmethod
    def sayhi2_2(self):#Static method, if you really want to pass on parameters, you can do so.
        print("---sayhi 2",self.name)
    @classmethod
    def sayhi3(self):#It can be invoked without instantiation. It can't access instance data. When it accesses the data in instantiation (self.name), it will report an error.
        print("---sayhi 3",self.age,self.name)
    @property#Turning a function into a static property
    def sayhi4(self):
        print("---sayhi 4",self.name)
        return 'test'

m = MyClass()
m.sayhi2()
m.sayhi2_2(m)    #Input parameters into the call
print(m.sayhi4)
# m.sayhi3()
# MyClass.sayhi3()

Class attribute method application:

class Attribute(object):
    def __init__(self,name):
        self.name= name
        self.__food= None
    @property     #Turning a class's methods into static attributes of a class
    def eat(self):
        print("%s eating %s......" %(self.name,self.__food))

    @eat.setter   #modify attribute
    def eat(self,food):
        print("set to food:",food)
        self.__food= food

    @eat.deleter
    def eat(self):  #Delete attributes
        del self.__food
d = Attribute("dayi")
# print(d.__dict__)
d.eat
d.eat = "noodle"
d.eat      #Call attributes after modifying attributes
del d.eat    #Delete attributes
d.eat        #Calling attributes when deleted will cause an error

6. Membership methods of classes

(1)__doc__

  Role: Get descriptive information about classes

class Dayi():
    """welcome to ...."""
    def func(self):
        """func"""
        pass
print(Dayi.__doc__)   #Print class description information

(2)__module__

  Function: Indicates the object of the current operation in that module

   __class__

  Role: What is the class representing the object being operated on?

from lib import Dayi
tim = Dayi

print(tim.__module__)
print(tim.__class__)

(3)__call__

  Function: The execution of the constructor is triggered by the creation of the object, that is, the object = the class name (); and the execution of the _call_ method is triggered by the object followed by brackets, that is, the object () or the class ()) ().

class Call():
    def __init__(self):
        pass
    def __call__(self, *args, **kwargs):
        print("__call__")

obj = Call()    #Execute _init__
obj()           #Execution of _call__

(4)__dict__

  Function: View all members of a class or object and display them in a dictionary.

(5)__str__

  Function: If a _str_ method is defined in a class, the return value of the method is output by default when printing an object.

class Dayi(object):
    def dayi123(self):
        print("dayi123")
    def __str__(self):
        return "hello"

obj = Dayi()
print(obj)   #The memory address of the output class without _str_, and the output value with _str_.

(6)__getitem__,__setitem__,__delitem__

  Function: Used for indexing operations, such as dictionaries. The above means to get, set, and delete data, respectively.

class Foo(object):
    def __init__(self):
        self.data = {}
    def __getitem__(self, key):
        print('__getitem__', key)
        return self.data.get(key)   #Read the value of key in the dictionary
    def __setitem__(self, key, value):
        print('__setitem__', key, value)
        self.data[key] = value       #Setting key in dictionary
    def __delitem__(self, key):
        print('__delitem__', key)
        del self.data[key] #Delete key data from data


obj = Foo()
obj['name'] = "hehe"
print(obj.__dict__)
print(obj.data)
# del obj["name"]    #Delete automatically triggers _delitem__
result = obj['k1']  # Automatic Trigger Execution _getitem__
print(obj.__dict__)
obj['k2'] = 'kk2'  # Automatic Trigger Execution _setitem__
print(obj.__dict__)  #When looking at the dictionary of a class, the dictionary content of the class is {data': {k2':'kk2','name':'hehe'}.
del obj['k2']
print(obj.__dict__)


Posted by olygolfer on Sun, 30 Jun 2019 15:58:04 -0700