Python object-oriented example


——Wang Yuyang Summary (Code_boy) November 16, 2018

1 classPerson:2     name='xxx'3     age=2045 p=Person()  #p is the instance object
 6 print(p.name,p.age)7 p.name="yyy"8 p.gender='male'9print(p.name,p.gender,p.age)10print(Person.name,Person.age)

p (instance object) does not affect the content in the Person class for value modification

Person.age='30'
print(Person.age)

class Person (class) The content in the Person class will be affected if it is worth modifying

'''

Access permissions (attributes of the class)

'''
class Person: #Person's name and age are public
name = 'james'
age=20

It is stipulated in python to add two underscores in front to become private

'''
'''
class Person:
__ name ='james' #private __name
age = 20

def show(self): #self >> oneself
print(self.__name,self.age) #Visit yourself and return normally

p=Person ()
p.show() #Need to call except show() function, otherwise it will reject the execution of show in class
print(Person.__name) # Access to private attributes in the class returns abnormally
print(p.age)

The same is true when there is a private function call! Private function, element can only be used in class

The commonly used method is to execute the call of the private properties in the function by calling the public function

'''

Case: Writing personal information and establishing object access attributes

1 classPerson:2     name ='xxx'3     gender ='x'4     age =056 p=Person()7print(p.name,p.gender,p.age)8print(Person.name,Person.gender,Person.age)910 p.name ='A'11 p.gender ='Male'12 p.age =201314 Person.name ='B'15 Person.gender ='Female'16 Person.age =211718print(p.name,p.gender,p.age)    #p instance object properties
19 print(Person.name,Person.gender,Person.age) #Person class attributes

Instance method

'''

1 classPerson:2     age =203     def show(self):4print(self.age)56 p.Person()

The instance method has at least one parameter, usually with a variable named (self) as the parameter (name can be customized)

The instance method is called through the instance object, for example: p.show()

If you use the class name to call, you need to manually pass the instance parameters, for example: Person.show(p)

The instance method is called to pass the instance object to its first parameter

1 classPerson:2     name ='james'3     age =1245     def getName(self):6return self.name
 78  def getAge(self):9return self.age
1011 p=Person()12print(p.getName(),p.getAge())   #Instance attribute object call
13 print(Person.getAge(p)) #Class name call
1 def show(self,s):   #Parameter passing
2 print(self,s)34 p.show('hi')    #'hi'Value passed to s
5 Person.show(p,'hello')  #hello to s'''

Class method

1 classPerson:2     age =203     @classmethod
4  def show(cls):5print(cls.age)67 p=Person()

Class methods should be decorated with @classmethod, and the first parameter is generally named cls (other names can be specified)

Class methods are usually called using the name of the class, for example: Person.show()

Class methods can also be called by instance methods, for example: p.show()

When a class method is called, the name of the class is passed to its first parameter

1 classPerson:2     __name ='james'3     __age =1245     @classmethod
 6  def show(self):7print(self)8print(self.__name,self.__age)910 Person.show()11 p=Person()12 p.show()'''

Static method

'''
definition:

1 classPerson:2     age =203     @staticmethod
4  def show():5print(Person.age)67 p =Person()

Static variable functions are modified by @staticmethod

Usually the name or instance of the class is used to call the static method, for example: Person.show(),p.show()

No parameters are passed to the function when calling a static function

1 classPerson:2     __name ='james'3     __age =1245     @staticmethod
 6  def show():     #Static without parameters
 7 print(Person.__name)89 p =Person()10 Person.show()11 p.show()

Classes, instances, and static methods are different-Person

1 classPerson:2     name ='xxx'3     gender ='x'4     age =05                     #Instance method
 6  def instanceShow(self):7print(self.name,self.gender,self.age)89     @classmethod    #Class method
10  def classShow(cls):11print(cls.name,cls.gender,cls.age)1213     @staticmethod   #Static method
14  def staticShow():15print(Person.name,Person.gender,Person.age)161718 p=Person()19 p.instanceShow()        #Instance method call
20 Person.classShow()      #Class method call
21 Person.staticShow()     #Static method call

Instance methods are generally called with instance objects
Class methods and static methods are generally called by class names

Object initialization

'''
Construction method (function)...>Complete function initialization
@ The constructor init(self, ...) is called when the object is generated,
Can be used to perform some initialization operations, do not need to be displayed to call, the system executes by default
If the user does not define a construction method, the system will execute the default construction method by itself
__ init__(self) is called when the object is generated
__ del__(self) is called when the object is released

1 classPerson:2     def __init__(self,n,a):3         self.name=n
4   aelf.age=a
56 p=Person('xxx',20)7print(p.name,p.age)

@ The destructor method del(self) is called when the object is released, and some operations to release resources can be performed in it
No need to show call

1 classPerson:2     def __init__(self,n,a):3         self.name = n
 4   self.age = a
 5  def __del__(self):6print('__del__',self.name,self.age)78 p=Person('xxx',20)9print(p.name,p.age)1011classPerson:12     def __init__(self):13print("__init__",self)14     def __del__(self):15print("__del__",self)1617 p=Person()

#__ init__ complete object initialization

1 classPerson:2     def __init__(self,n,g,a):       #n,g,a Reference unit
 3   self.name = n
 4   self.gender = g
 5   self.age = a
 67  def show(self):8print(self.name,self.gender,self.age)910 p=Person('james','male',20)     #After the p object is determined, the initialization (n, a, m) of the p object is completed
11 p.show()

Python stipulates: There can only be one constructor in a class

#...__ Set default parameters in init__

1 classPerson:2     def __init__(self,n='',g='male',a=0):3         self.name = n
 4   self.gender = g
 5   self.age = a
 67  def show(self):8print(self.name,self.gender,self.age)910 a =Person('james')11 b =Person('james','fenmale')12 c =Person('james','male',20)13 a.show()    #Result: james male 014 b.show()    #Results: james fenmale 015 c.show()    #Results: james male 2016# __init__If the default value is set in the parameter, the original value will be overwritten after the new content is passed.'''

Case: Date class MyDate

1 classMyDate:2     __months =[0,31,28,31,30,31,30,31,31,30,31,30,31]3     def __init__(self,y,m,d):4if(y<0):5print("Error:Invalid year")6if(m<1 or m>12):7print("Error:Invalid month")8if(y%400==0 or y%4==0 and y%100!=0):9             MyDate.__months[2]=2910else:11             MyDate.__months[2]=281213if d<1 or d>MyDate.__months[m]:14print("Error:Invalid date")15         #After the date, month, and year are all legal, create the attributes (content) of the class
16   self.year = y
17   self.months = m
18   self.day = d
19  def show(self,end='\n'):20print("%d-%d-%d"%(self.year,self.months,self.day),end = end)2122 p =MyDate(2018,11,19)23 p.show()

Class inheritance

Derivation and inheritance: Student: name gender age

1 classPerson:2     def __init__(self,name,gender,age):3         self.name = name
 4   self.gender = gender
 5   self.age = age
 67  def show(self,end='\n'):8print(self.name,self.gender,self.age)910classStudent(Person):11     def __init__(self,name,gender,age,major,dept):12         Person.__init__(self,name,gender,age)13         self.major = major
14   self.dept = dept
1516  def show(self):17         Person.show(self,'')18print(self.major,self.dept)1920 s =Student('james','male',20,'softwart','computer')21 s.show()222324'''
25 result:
26 james male 2027 softwart computer
28'''

Inherited class constructor:

From the definition of the Strdent class above, it can be seen that in addition to the constructor of the derived class, in addition to completing its own new addition
In addition to the initialization of the major and dept properties, the Person constructor of the base class must be called, and the call must be displayed
Namely: Person.init(self,neme,gender,age)
Call Person's init function directly through the class name Person, and provide the required 4 functions
The constructor of the base class will not be automatically called when the class is inherited, and the call must be displayed

Inheritance of attribute methods:

If there is an instance method in a base class, you can redefine exactly the same instance method in the inherited class.
For example, Person has a show method, and Student has the same show method. They will not be confused
We call the show of the Student class overrides the show of the Person
—Of course, the instance method of a base class can also not be overridden, the derived class will inherit the instance method of this base class

1 classPerson:2     className ='Person'    #Own instance attributes
 3  def __init__(self,name,gender,age):4         self.name = name
 5   self.gender = gender
 6   self.age = age
 78  def show(self,end='\n'):9print(self.name,self.gender,self.age)1011     @classmethod        #Class method modification
12  def classClassName(cls):13print(cls.className)1415     @staticmethod       #Static method decoration
16  def staticClassName():17print(Person.className)1819     def display(self):20print('display')2122classStudent(Person):23     #className ='Student'24     def __init__(self,name,gender,age,major,dept):25         Person.__init__(self,name,gender,age)26         self.major = major
27   self.dept = dept
2829  def show(self):30         Person.show(self,'')31print(self.major,self.dept)3233 s =Student('A','male',20,'software','computer')34 s.show()35print(Student.className)    #If there is no Student itself, the upper level (Person) is displayed
36 Student.classClassName()37 Student.staticClassName()3839 s.display() #Instance call
404142 # Result description: Student inherits the instance, static, and class (attribute) methods of Person
43 # result:
44'''
45 A male 2046 software computer
47 Person
48 Person
49 Person
50 display
51'''

Case: year, month, day + hour, minute, second

1 classMyDate:2     __months =[0,31,28,31,30,31,30,31,31,30,31,30,31]3     def __init__(self,y,m,d):4if(y<0):5print("Error:Invalid year")6if(m<1 or m>12):7print("Error:Invalid month")8if(y%400==0 or y%4==0 and y%100!=0):9             MyDate.__months[2]=2910else:11             MyDate.__months[2]=281213if d<1 or d>MyDate.__months[m]:14print("Error:Invalid date")15         #After the date, month, and year are all legal, create the attributes (content) of the class
16   self.year = y
17   self.months = m
18   self.day = d
19  def show(self,end='\n'):20print("%d-%d-%d"%(self.year,self.months,self.day),end = end)2122classMyDateTime(MyDate):23     def __init__(self,y,mo,d,h,mi,s):24         MyDate.__init__(self,y,mo,d)25if(h<0  or  h>23  or  mi<0  or  mi>59  or  s<0  or  s>59):26print("Error:Invalid time")27         self.hour = h
28   self.minute = mi
29   self.second = s
3031  def show(self):32         MyDate.show(self,'\t')33print("%d:%d:%d"%(self.hour,self.minute,self.second))343536 p =MyDateTime(2018,11,19,21,21,54)37 p.show()3839 #Results: 2018-11-1921:21:54

Recommended Posts

Python object-oriented example
Python object-oriented basics
Python object-oriented magic method
Python3.7 debugging example method
Python interpolate interpolation example
Python negative modulus operation example
Python3 logging log package example
Python regular expression example code
Python output mathematical symbols example
Analysis of Python object-oriented programming
Python iterable object de-duplication example
Python one-dimensional two-dimensional interpolation example
What is object-oriented in python
Python draw bar graph (bar graph) example
Python right alignment example method
Python waterfall line indicator writing example
Python list comprehension operation example summary
Python ATM function implementation code example
Python example to calculate IV value
Python decorator simple usage example summary
Example operation of python access Alipay
How to understand python object-oriented programming
Python tcp transmission code example analysis
Python requests module session code example
Python verification code interception identification code example
Python multithreading
Python FAQ
Python3 dictionary
Python3 module
python (you-get)
Python string
Python basics
Python descriptor
Python basics 2
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python toolchain
Python crawler example to get anime screenshots
Python multitasking-coroutine
Python overview
python introduction
Learn Python in one minute | Object-oriented (Chinese)
Python analytic
Python basics
Example of python calculating derivative and plotting
07. Python3 functions
Python basics 3
Example method of reading sql from python
Python multitasking-threads
Python functions
python sys.stdout
Python example method to open music files
python operator
Python entry-3
Centos 7.5 python3.6
Python string