python object oriented

Keywords: Operation & Maintenance vim

1, Classes and objects

  • Class is the reflection of the entity of the real world or the thinking world in the computer
  • It encapsulates data and operations on it
  • Compare a class to a template, through which many objects can be generated


2, Constructor

$ vim s3.py

class Student():
    name = ''
    age = 0

    def do_homework(self):
        print('homework')

student1 = Student()
student2 = Student()
student3 = Student()

print(id(student1))
print(id(student2))
print(id(student3))


#implement
#python2.7 s3.py 

4305810496
4305810640
4305810712

//Note: use student template to create objects, and student template to create different objects;

 
Step 1. Several objects are different after instantiation

1.stay Student Definition__init__Function, different from other functions__init__Is fixed, also known as a constructor

$ vim s4.py

class Student():
    name = ''
    age = 0

    def __init__(self):
        print('student')


    def do_homework(self):
        print('homework')

student1 = Student()



#implement
//Note: the print result is student, i.e. None
$ python2.7 s3.py 
student



2.Implement different objects,__init__()Not only can it be defined self,You can also define name,age And so on, in order to achieve different objects


Step 2. Instance variable and class variable

Note: class variables are only associated with classes; instance variables are associated with objects

1.Instance variable and class variable cause the printing result to be null

class Student():
    name = ''
    age = 0

    def __init__(self,name,age):
        print('student')
        name = name
        age = age


    def do_homework(self):
        print('homework')

student1 = Student('Xiao Ming',18)
print(student1.name)
 


# implement
$ python2.7 s3.py 
student


2.Save characteristic values

class Student():
    name = ''
    age = 0

    def __init__(self,name,age):
        print('student')
        self.name = name
        self.age = age


    def do_homework(self):
        print('homework')

student1 = Student('Xiao Ming','18')
print(student1.name)


#Execute (printed successfully)

$ python2.7 s3.py 
//Xiao Ming

//Note: use self to save the eigenvalues. These two pieces of code actually define two instance variables, which are class independent and object dependent
self.name = name
self.age = age



3.Print variables of class at the same time

# coding=utf-8
class Student():
    name = 'yunming'
    age = 0

    def __init__(self,name,age):
        #print('student')
        self.name = name
        self.age = age


    def do_homework(self):
        print('homework')

student1 = Student('Xiao Ming',18)
print(student1.name)
 
print(Student.name) //Print class variable


#implement
#python2.7 s3.py 

//Xiao Ming
yunming

Posted by kennethl on Tue, 05 May 2020 12:39:56 -0700