Python introductory tutorial | Python object-oriented

Preface

Python has been an object-oriented language from the beginning, and because of this, it is easy to create classes and objects in Python. In this chapter we will introduce object-oriented programming in Python in detail.

If you have not been exposed to object-oriented programming languages ​​before, you may need to first understand some basic features of object-oriented languages ​​and form a basic object-oriented concept in your mind. This will help you learn Python more easily. Object-Oriented Programming.

Next, let's first briefly understand some basic characteristics of object-oriented.

Introduction to object-oriented technology

  • Class : Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes.
  • Method : Function defined in the class.
  • Class variables : Class variables are public throughout the instantiated object. Class variables are defined in the class and outside the function body. Class variables are generally not used as instance variables.
  • Data members : Class variables or instance variables are used to handle data related to the class and its instance objects.
  • Method rewriting : If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method override, also known as method rewriting.
  • Local variables : Variables defined in methods only affect the class of the current instance.
  • Instance variables : In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self.
  • Inheritance : A derived class inherits the fields and methods of a base class. Inheritance also allows an object of a derived class to be treated as a base class object. For example, there is such a design: an object of type Dog is derived from the Animal class, which simulates the "is-a" relationship (for example, Dog is an Animal).
  • Instantiation : Create an instance of a class, a specific object of the class.
  • Object : An instance of a data structure defined by a class. Objects include two data members (class variables and instance variables) and methods.
    Compared with other programming languages, Python adds class mechanisms without adding new syntax and semantics as much as possible.

Classes in Python provide all the basic functions of object-oriented programming: the inheritance mechanism of classes allows multiple base classes, derived classes can override any method in the base class, and methods with the same name in the base class can be called.

Objects can contain any amount and type of data.

class definition

The syntax format is as follows:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

Once a class is instantiated, its properties can be used. In fact, after a class is created, its properties can be accessed through the class name.
Code example:

class MyClass:
    """一个简单的类实例"""
    i = 12345
    def f(self):
        return 'hello world'

object

Objects support two operations: property reference and instantiation.

Property references use the same standard syntax as all property references in Python: obj.name.

After a class object is created, all names in the class namespace are valid attribute names. So if the class definition looks like this:

#!/usr/bin/python3
 
class MyClass:
    """一个简单的类实例"""
    i = 12345
    def f(self):
        return 'hello world'
 
# 实例化类
x = MyClass()
 
# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())

The above creates a new class instance and assigns the object to the local variable x, which is an empty object.

The output result of executing the above program is:

The attribute i of the MyClass class is: 12345
The output of the method f of the MyClass class is: hello world

Classes have a special method ( constructor ) called _ init _() , which is automatically called when the class is instantiated, like this:

def __init__(self):
    self.data = []

The class defines the _ init _() method, and the instantiation operation of the class will automatically call the _ init _() method. When the class MyClass is instantiated as follows , the corresponding _ init _() method will be called:

x = MyClass()

Of course, the _ init _() method can have parameters, and the parameters are passed to the instantiation operation of the class through init (). For example:

#!/usr/bin/python3
 
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i)   # 输出结果:3.0 -4.5

self represents an instance of a class, and non-
class methods have only one special difference from ordinary functions - they must have an additional first parameter name, which by convention is self .

class Test:
    def prt(self):
        print(self)
        print(self.__class__)
 
t = Test()
t.prt()

The execution result of the above example is:

<_main_.Test object at 0x000001B55C75B610>
<class ‘_main_.Test’>

From the execution results, it is obvious that self represents an instance of the class and the address of the current object, while self.class points to the class.

self is not a python keyword. If we replace it with runoob, it can be executed normally:

class Test:
    def prt(tarzan):
        print(tarzan)
        print(tarzan.__class__)
 
t = Test()
t.prt()

The execution result of the above example is:

<_main_.Test object at 0x000001702A38B650>
<class ‘_main_.Test’>

class methods

Within a class, use the def keyword to define a method. Unlike general function definitions, class methods must contain the parameter self , which is the first parameter. Self represents an instance of the class.

#!/usr/bin/python3
 
#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁,体重 %d 公斤。" %(self.name,self.age,self.__weight))
 
# 实例化类
p = people('tarzan',30,70)
p.speak()

The output result of executing the above program is:

tarzan said: I am 30 years old and weigh 70 kg

inherit

Python also supports class inheritance. If a language does not support inheritance, classes are meaningless. The definition of the derived class is as follows:

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

The subclass (DerivedClassName) will inherit the properties and methods of the parent class (BaseClassName).

BaseClassName (the base class name in the instance) must be defined in the same scope as the derived class. In addition to classes, you can also use expressions, which is useful when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName):

Code example

#!/usr/bin/python3
 
#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
 
 
 
s = student('ken',10,60,3)
s.speak()

The output result of executing the above program is:

ken said: I am 10 years old and I am in grade 3

multiple inheritance

Python also has limited support for multiple inheritance forms. The class definition of multiple inheritance looks like the following example:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>
  • You need to pay attention to the order of the parent class in parentheses. If there is the same method name in the parent class, but it is not specified when using it in the subclass, python searches from left to right. That is, when the method is not found in the subclass, it searches from left to right. Whether the parent class contains methods.

Code example

#!/usr/bin/python3
 
#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
 
#另一个类,多继承之前的准备
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
 
#多继承
class sample(speaker,student):
    a =''
    def __init__(self,n,a,w,g,t):
        student.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)
 
test = sample("Tim",25,80,4,"Python")
test.speak()   #方法名同,默认调用的是在括号中参数位置排前父类的方法

The output result of executing the above program is:

My name is Tim, I am a speaker, and the topic of my speech is Python

Method overriding

If the function of your parent class method cannot meet your needs, you can override the method of your parent class in the subclass. Examples are as follows:

#!/usr/bin/python3
 
class Parent:        # 定义父类
   def myMethod(self):
      print ('调用父类方法')
 
class Child(Parent): # 定义子类
   def myMethod(self):
      print ('调用子类方法')
 
c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法
super(Child,c).myMethod() #用子类对象调用父类已被覆盖的方法
  • The super() function is a method used to call the parent class (super class).

The output result of executing the above program is:

Call subclass method
Call parent class method

If you need the constructor of the parent class in a subclass, you need to explicitly call the constructor of the parent class, or do not override the constructor of the parent class.

Subclasses do not override _ init _. When instantiating a subclass, _ init _ defined by the parent class is automatically called.

class Father(object):
    def __init__(self, name):
        self.name=name
        print ( "name: %s" %( self.name) )
    def getName(self):
        return 'Father ' + self.name
 
class Son(Father):
    def getName(self):
        return 'Son '+self.name
 
if __name__=='__main__':
    son=Son('runoob')
    print ( son.getName() )

The output is:

name: runoob
Son runoob

If _ init _ is overridden and the subclass is instantiated, the _ init _ defined by the parent class will not be called. The syntax format is as follows:

class Father(object):
    def __init__(self, name):
        self.name=name
        print ( "name: %s" %( self.name) )
    def getName(self):
        return 'Father ' + self.name
 
class Son(Father):
    def __init__(self, name):
        print ( "hi" )
        self.name =  name
    def getName(self):
        return 'Son '+self.name
 
if __name__=='__main__':
    son=Son('runoob')
    print ( son.getName() )

The output is:

hi
Son runoob

If you override _ init _ and want to inherit the constructor method of the parent class, you can use the super keyword:

super(子类,self).__init__(参数1,参数2....)

There is also a classic way of writing:

父类名称.__init__(self,参数1,参数2...)

Code example

class Father(object):
    def __init__(self, name):
        self.name=name
        print ( "name: %s" %( self.name))
    def getName(self):
        return 'Father ' + self.name
 
class Son(Father):
    def __init__(self, name):
        super(Son, self).__init__(name)
        print ("hi")
        self.name =  name
    def getName(self):
        return 'Son '+self.name
 
if __name__=='__main__':
    son=Son('tarzan')
    print ( son.getName() )

The output is:

name: tarzan
hi
Son tarzan

Class properties and methods

Class private properties

__private_attrs: Beginning with two underscores, declares that the attribute is private and cannot be used or directly accessed outside the class. When using self.__private_attrs in a method inside a class.

class methods

Inside a class, use the def keyword to define a method. Unlike general function definitions, class methods must contain the parameter self, which is the first parameter. Self represents an instance of the class.

The name of self is not fixed, you can also use this , but it is best to use self according to the convention .

private method of class

__private_method: Starting with two underscores, the method is declared as a private method and can only be called inside the class, not outside the class. self.__private_methods.


Examples of private properties of the class are as follows:

#!/usr/bin/python3
 
class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量
 
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)
 
counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount)  # 报错,实例不能访问私有变量

The output result of executing the above program is:

1
2
2
Traceback (most recent call last):
File “C:\Users\Lenovo\Desktop\test.py”, line 14, in
print (counter.__secretCount) # Error, instance cannot access private variables
^^^^^ ^^^^^^^^^^^^^^^^
AttributeError: 'JustCounter' object has no attribute '__secretCount'

Examples of private methods of the class are as follows:

#!/usr/bin/python3
 
class Site:
    def __init__(self, name, url):
        self.name = name       # public
        self.__url = url   # private
 
    def who(self):
        print('name  : ', self.name)
        print('url : ', self.__url)
 
    def __foo(self):          # 私有方法
        print('这是私有方法')
 
    def foo(self):            # 公共方法
        print('这是公共方法')
        self.__foo()
 
x = Site('洛阳泰山博客', 'https://tarzan.blog.csdn.net')
x.who()        # 正常输出
x.foo()        # 正常输出
x.__foo()      # 报错

The above code execution output:

name  :  洛阳泰山博客
url :  https://tarzan.blog.csdn.net
这是公共方法
这是私有方法
Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\test.py", line 22, in <module>
    x.__foo()      # 报错
    ^^^^^^^
AttributeError: 'Site' object has no attribute '__foo'
  • Exception reason External method cannot call private method.

Class private methods:

_ init _: Constructor, called when generating an object
_ del _: Destructor, used when releasing an object
_ repr _: Print, convert
_ setitem _: Assign value according to index
_ getitem _: Get value according to index
_ len _: Get length
_ cmp _: Comparison operation
_ call _: Function call
_ add _: Addition operation
_ sub _: Subtraction operation
_ mul _: Multiplication operation
_ truediv _: Division operation
_ mod _: Remainder operation
_ pow _: Multiplication square

Operator overloading

Python also supports operator overloading. We can overload proprietary methods of classes. Examples are as follows:

#!/usr/bin/python3
 
class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b
 
   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)
 
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

The result of executing the above code is as follows:

Vector(7,8)

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/133024540