程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Object oriented programming in Python

編輯:Python

object-oriented :Object Oriented Programming, abbreviation OOP, Object oriented programming .

class (Class) And the object (Object)

Class is used to describe a collection of objects with the same properties and methods . Object is a concrete instance of a class .

such as , Students have names and grades , Then the name and score are common attributes , Then you can design a class , Used to record students' names and grades .

Here we explain the properties and methods

  • attribute :Attribute, Used to describe the public properties of all objects , Such as the student's name and score .
  • Method :Method, The functions contained in the class , Also called class function , Different from functions outside the class , Used to realize some functions , For example, print out the student's name and score .

Use key words class To create a class

class Student():
def __init__(self,name,score):
self.name = name
self.score = score def out(self):
print("%s:%s"%(self.name,self.score)

In the above cases , It just defines a class , The computer does not create storage space .

Only complete the instantiation of the class , To create a concrete object of the class , And allocate storage space . So , Object is an instance of a class . Next, create an object , Just add two lines of code

Student1 = Student('Anny','100')
Student2 = Student('Mike','90')

thus ,Student It's a class ,student1 and student2 Is the concrete object of the class created . When you have the above code ,Python Automatically called init Initial self constructing function to create concrete object . keyword self Is a very important parameter , Represents the creation of the function itself .

When a concrete object is created , You can use Student1.name and Student1.score To get the student's name and score respectively , You can also call methods directly Student1.out() To get all the information .

Class variables and instance variables

Suppose you now need to add a counter , The counter is incremented whenever a student is added 1.

This counter does not belong to a student , It's an attribute of a class , So it's called class .

The name and score belong to each student , So it's called instance variable , Also called object variables . Under normal circumstances , This adds a counter

class Student():
​
number = 0
​
def __init__(self,name,score):
self.name = name
self.score = score
number = number + 1
​
def show(self):
print("%s:%s"%(self.name,self.score))
​
student1 = Student('Anny',100)
student2 = Student('Mike',90)
​
print(student1.name)

there number It's a class variable , So put it outside the method ,name and score Is instance variable , So put it in the method .

Class variables and instance variables are very different , It's not the same way .

Class variables :class variables, Class variables are common to the entire instantiated object , Class variables are defined in classes , And outside the function . The specific method to access or call class variables is the class name . Variable name , perhaps self.class. Variable name ,self.class. Automatically return the class name of each object . Instance variables :instance variables, Variables defined within a function , Belonging to a specific object , The method to access or call the instance variable is the object name . Variable name , perhaps self. Variable name .

Executing the above code will find an error UnboundLocalError: local variable 'number' referenced before assignment Poor English , Translated by a cloud : It roughly means local variable number Reference to previous tasks , So , If you want to call a variable belonging to a class number, Then use Student.number perhaps self.class.number

Revised as follows :

class Student():
​
number = 0
​
def __init__(self,name,score):
self.name = name
self.score = score
Student.number = Student.number + 1
​
def show(self):
print("%s:%s"%(self.name,self.score))
​
student1 = Student('Anny',100)
student2 = Student('Mike',90)
​
student1.show()
print(student2.number)

Class method

Some variables belong only to classes , Some methods only belong to classes , Not belonging to a specific object . It's not hard to find out , There are all methods belonging to objects self Parameters of , such as init(self)、show(self) etc. , And in the class , Then use cls, And self similar , It represents the class itself , General plus @classmethod Modifier to illustrate .

Here, a custom class method is used to print the number of students

class Student():
​
number = 0
​
def __init__(self,name,score):
self.name = name
self.score = score
Student.number = Student.number + 1
​
def show(self):
print("%s:%s"%(self.name,self.score)) @classmethod
def people(cls):
print(" Altogether %s Famous student "%Student.number)
​
student1 = Student('Anny',100)
student2 = Student('Mike',90)
​
student1.show()
student2.show()
Student.people()

Private properties and private methods of class

Private properties and private methods in the class are double underlined __ At the beginning , Private properties and methods cannot be used or accessed directly outside the class . take score Become private , then print(Student.score), You'll find that the report is wrong . But the call show I don't make a mistake when I'm in the hospital , This is because show Is the function in the class , So you can access private variables .

The same is true for private methods , It is worth noting that , Private methods must contain self Parameter as the first parameter .

In object-oriented programming , It is often rare for external classes to have direct access to properties and methods inside a class , Instead, provide some buttons to the outside , Access to its internal members , To ensure the safety of the program , This is called encapsulation .

@property
def scores(self):
print(" The student's grade is %s"%self.score)

After adding the decorator, it can be called directly without parentheses .

Class inheritance

The biggest advantage of object-oriented programming is to avoid duplicate code , That is to reuse a piece of code , One way is to inherit .

First define a base class or parent class , Re pass class Class name ( Parent class ):pass Create subclass , thus , The subclass obtains all the properties and methods of the parent class , This phenomenon is called inheritance .

Write another piece of code , use Schoolmember Represents the parent class , Name and age are attributes of everyone , However, teachers are paid (salary) This proprietary property , Students have scores (score) This proprietary property

# Create a parent school member SchoolMemberclass SchoolMember:
​
def __init__(self, name, age):
self.name = name
self.age = age def tell(self):
# Print personal information
print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")# Create a subclass teacher Teacherclass Teacher(SchoolMember):
​
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age) # Use the parent class to initialize
self.salary = salary # Method rewriting
def tell(self):
SchoolMember.tell(self)
print('Salary: {}'.format(self.salary))# Create subclass students Studentclass Student(SchoolMember):
​
def __init__(self, name, age, score):
SchoolMember.__init__(self, name, age)
self.score = score def tell(self):
SchoolMember.tell(self)
print('score: {}'.format(self.score))
​
teacher1 = Teacher("John", 44, "$60000")
student1 = Student("Mary", 12, 99)
​
teacher1.tell() # Print Name:"John" Age:"44" Salary: $60000student1.tell() # Name:"Mary" Age:"12" score: 99

From the above code, it is not difficult to see

  • In the process of creating subclasses , The constructor of the parent class needs to be called manually init To complete the creation of subclasses .
  • When calling the parent class method in a subclass , You need to prefix the class name of the parent class , And must bring self Parameter variable . example SchoolMember.tell(self).
  • If a subclass calls each method or property ,Python Will first look in the parent class , If you can't find it, you will go to the subclass to find .

== In the actual project , A subclass can inherit more than one parent class .==

Use super() Keyword calls the parent class

Can be used in subclasses super Keyword directly calls the property or method in the parent class , Simplify the code , It also reflects that life is short , I use Python The purpose of .

# Create subclass students Studentclass Student(SchoolMember):
​
def __init__(self, name, age, score):
SchoolMember.__init__(self, name, age)
self.score = score def tell(self):
super().tell() # Equate to SchoolMember.tell(self)
print('score: {}'.format(self.score))

In the example above , The student subclass called the parent class tell Method , Equate to SchoolMember.tell(self), Use super Key words are used , You need to remove the... In parentheses self.

This is the end of the sharing , If it helps you , Please pay attention before you leave ~ Thank you for reading .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved