current position:Home>[introduction to Python 3 5: basic object-oriented]

[introduction to Python 3 5: basic object-oriented]

2022-02-02 15:17:56 Overflow tears

brief introduction

  • Pre knowledge : Basic object-oriented concept
    This article mainly describes how to P y t h o n 3 Python3 Python3 Using object-oriented in
  • Hou Wenba a t t r i b u t e attribute attribute Translate into Field , hold p r o p e r t y property property Translate into attribute , These are two different contents

Simple classes use

  • Create a class
class MyClass:
    val = 10	#  Define a normal sub segment 
    __val2 = 10	#  Defines a private sub segment 
    def func(self):		#  Define a method 
	    return self.val #  return  val  Value 
	def __func2(self):	#  Defines a private method 
		return self.val2

#  Instantiate the class 
c = MyClass()

#  Access the fields of the class , Method of calling class 
print(c.val)
print(c.func())

Be careful , The first parameter of a method of a class must be given self , Names can be arbitrary , But specifications are generally named self
This represents an instance of a class , Represents the address of the current object , Not a class .

  • Class has a special constructor __init()__
class MyClass:
    def __init__(self):		#  A simple constructor 
    	self.val = 10
    def func(self):
	    return self.val

Of course , Constructors can also take arguments , Like other languages .

class MyClass:
    def __init__(self,arg1,arg2):
    	self.val1 = arg1
    	self.val2 = arg2

Inherit

  • The definition of derived classes is as follows :
class DerivedClassName(BaseClassName):
	def __init__(self):
		BaseClassName.__init__(self)	#  Call the constructor of the parent class 
	def speak(self):	#  Override the parent method 
		pass

Multiple inheritance

  • P y t h o n Python Python Support for multiple inheritance , The definition is as follows :
class DerivedClassName(Base1,Base2,Base3):
	pass

Operator overloading

  • We can overload the proprietary methods of a class
    For example, the following proprietary methods :
__add__
__sub__
__mul__
__truediv__
__mod__
__pow__

For example, it can be written as :

def __add__(self,other):
	return self.a + other.a

copyright notice
author[Overflow tears],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202021517538038.html

Random recommended