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

Python -- object oriented preliminary

編輯:Python

Catalog

Object oriented thinking

Object meaning

The definition of a class

__init__ Construction method and __new__ Method

Instance properties and instance methods

Instance attributes

Example method

The difference between function and method

Other operating :

Class object

Class properties

Class method

Static methods

__del__ Method ( Destructor ) And garbage collection mechanisms

__call__ Methods and callable objects

Method is not overloaded

The dynamics of methods

Private properties and private methods ( Implement encapsulation )

@property decorate


Object oriented thinking

         Object oriented focuses on “ The relationship between objects in software ”, It's a kind of “ Designer ” thinking , Suitable for writing Large scale programs . Object oriented thinking is more in line with people's thinking mode . The first thing we think about is “ How to design this thing ?” Think about making cars , We'll think about it first “ How to design the car ?”, instead of “ How to build a car step by step ”.

Object meaning

         Put different types of data 、 Method ( It's a function ) Put it together , It's the object .

The definition of a class

         The syntax format of the definition class is as follows :

        class Class name :

                 The class body

         The point is as follows :

        1. Class name must match “ identifier ” The rules of ; General rules , title case , Use more than one word “ Hump principle ”.

        2. In the class body, we can define properties and methods .

        3. Attributes are used to describe data , Method ( It's a function ) Used to describe operations related to these data .

Definition of a typical class :

class Student:
def __init__(self,name,score): # The first parameter of the constructor must be self
self.name = name # Instance attributes
self.score = score
def say_score(self): # Example method
print(self.name,' My score is :',self.score)
s1 = Student(' Zhang San ',80) #s1 Is the instance object , Automatically call __init__() Method
s1.say_score()
Zhang San's score is : 80

__init__ Construction method and __new__ Method

         Create objects , We need to define the constructor __init__() Method . Construction methods are used to perform “ The initialization of the instance object do ”, That is, after the object is created , Initialize the relevant properties of the current object , No return value .

        __init__() The main points are as follows :

        1. Fixed name , It has to be for :__init__()

        2. The first parameter is fixed , It has to be for :self. self It refers to the instance object just created .

        3. Constructors are usually used to initialize instance properties of instance objects , The following code initializes the instance property :name and score.

def __init__(self,name,score):
self.name = name # Instance attributes
self.score = score

        4. adopt “ Class name ( parameter list )” To call the constructor . After calling , Return the created object to the corresponding variable . such as :s1 = Student(' Zhang San ',80)

        5. __init__() Method : Initialize the created object , Initialization refers to :“ Assign values to instance properties ”

        6. __new__() Method : For creating objects , But we generally don't need to redefine the method .

        7. If we don't define __init__ Method , The system will provide a default __init__ Method . If we define with parameters Of __init__ Method , The system does not create a default __init__ Method .

Instance properties and instance methods

Instance attributes

Instance properties are properties that are subordinate to instance objects , Also known as “ Instance variables ”. His use has the following points :

        1. Instance properties are generally in __init__() Method is defined by the following code : self. Instance property name = Initial value

        2. In other instance methods of this class , through self Visit : self. Instance property name

        3. After the instance object is created , Access through instance objects : obj01 = Class name () # Create objects , call __init__() Initialization property obj01. Instance property name = value # You can assign values to existing properties , You can also add new attributes

Example method

Instance methods are methods that are subordinate to instance objects . The definition format of the instance method is as follows :

def Method name (self [, Parameter list ]):

         The body of the function

The calling format of the method is as follows :

         object . Method name ([ Argument list ])

The main points of :

1. When defining instance methods , The first parameter must be self. Same as before ,self Refers to the current instance object .

2. When an instance method is called , Don't need and can't give self The ginseng .self Parameters are automatically transferred by the interpreter

The difference between function and method

1. They are all statement blocks used to complete a function , The essence is the same .

2. Method call , Call through object . Method is subordinate to a specific instance object , Ordinary functions do not have this feature .

3. Intuitively , Method definition needs to pass self, The function doesn't need

Other operating :

1. dir(obj) You can get all the properties of the object 、 Method

2. obj.__dict__ Object's attribute dictionary

3. pass Empty statement

4. isinstance( object , type ) Judge “ object ” Is it right? “ Specify the type ”

Class object

When the interpreter executes class When the sentence is , A class object will be created .

Class properties

         Class attribute is subordinate to “ Class object ” Properties of , Also known as “ Class variables ”. because , Class properties are subordinate to class objects , Sure Shared by all instance objects .

How class properties are defined :

        class Class name :

                 Class variable name = Initial value

Inside or outside a class , We can go through :“ Class name . Class variable name ” Read and write .

Class method

Class methods are subordinate to “ Class object ” Methods . Class method through decorator @classmethod To define , The format is as follows

@classmethod
def Class method name (cls [, Parameter list ]) :
The body of the function 

The point is as follows :

1. @classmethod Must be on the line above the method

2. first cls There has to be ;cls Refers to “ Class object ” In itself ;

3. Call class method format :“ Class name . Class method name ( parameter list )”. In the parameter list , Don't need and can't give cls Pass on value .

4. Accessing instance properties and instance methods in class methods can lead to errors

5. When a subclass inherits a parent class method , Pass in cls It's a subclass object , Instead of the parent object

Static methods

        “ Static methods ” It's no different from defining ordinary functions in modules , It's just “ Static methods ” Put it in “ Class name is empty Inside ”, Need to pass through “ Class call ”.

Static method through decorator @staticmethod To define , The format is as follows

@staticmethod
def Static method name ([ Parameter list ]) :
The body of the function 

The point is as follows :

1. @staticmethod Must be on the line above the method

2. Call static method format :“ Class name . Static method name ( parameter list )”.

3. Accessing instance properties and instance methods in static methods can lead to errors

__del__ Method ( Destructor ) And garbage collection mechanisms

class Person:
def __del__(self):
print(" Destroy object :{0}".format(self))
p1 = Person()
p2 = Person()
del p2
print(" Program end ")
Destroy object :<__main__.Person object at 0x00000215C883E620>
Program end
Destroy object :<__main__.Person object at 0x00000215C883E650>

__call__ Methods and callable objects

Defined __call__ Object of method , be called “ Callable object ”, That is, the object can be called like a function .

class SalaryAccount:
''' Salary calculation '''
def __call__(self, salary):
yearSalary = salary*12
daySalary = salary//30
hourSalary = daySalary//8
return dict(monthSalary=salary,yearSalary=yearSalary,daySalary=daySalary,hourSalary=hourSalary)
s = SalaryAccount()
print(s(5000))
{'monthSalary': 5000, 'yearSalary': 60000, 'daySalary': 166, 'hourSalary': 20}

Method is not overloaded

The dynamics of methods

Python It's dynamic language , We can dynamically add new methods to classes , Or dynamically modify the existing methods of the class .

class Person:
def work(self):
print(" Work hard !")
def play_game(self):
print("{0} Play a game ".format(self))
def work2(self):
print(" Work hard , Work hard !")
Person.play = play_game
Person.work = work2
p = Person()
p.play()
p.work()
<__main__.Person object at 0x0000020EDD0BE9B0> Play a game
Work hard , Work hard !

You can see ,Person Dynamic new play_game Method , And with work2 To replace the work Method .

Private properties and private methods ( Implement encapsulation )

1. Usually we agree , Attributes starting with two underscores are private . Others are public .

2. Class can access private properties ( Method )

3. Private properties cannot be accessed directly outside the class ( Method )

4. Class can be passed “_ Class name __ Private property ( Method ) name ” Access private properties ( Method )

class Employee:
def __init__(self,name,age):
self.name = name
self.__age = age
def __work(self):
print(" Work ! Work hard , To make money , Marry a daughter-in-law !")
p1 = Employee("giaohu",18)
print(p1.name)
print(p1._Employee__age)
#print(p1.__age) # Direct access to private properties , Report errors
#p1.__sleep() # Direct access to private methods , Report errors
giaohu
18

@property decorate

@property You can change the calling mode of a method into “ Calling a ”.

class Employee:
def __init__(self,name,salary):
self.name = name
self.__salary = salary
@property # amount to salary Attribute getter Method
def salary(self):
print(" The monthly salary is {0}, The annual salary is {1}".format(self.__salary,(12*self.__salary)))
return self.__salary;
@salary.setter
def salary(self,salary): # amount to salary Attribute setter Method
if(0<salary<1000000):
self.__salary = salary
else:
print(" Salary entry error ! Only in 0-1000000 Between ")
emp1 = Employee("giaohu",100)
print(emp1.name,emp1.salary)
emp1.salary = -200
The monthly salary is 100, The annual salary is 1200
giaohu 100
Salary entry error ! Only in 0-1000000 Between


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