[Python] Python Series Tutorials--Python3 Object-Oriented (28)

foreword

Past review:

Python has been designed as an object-oriented language from the beginning, and because of this, it is very easy to create a class and object 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 understand some basic features of object-oriented languages ​​first, and form a basic object-oriented concept in your mind, which will help you learn Python more easily. Object-Oriented Programming.

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

Introduction to Object-Oriented Technology

  • Class (Class): Used to describe a collection of objects with the same properties and methods. It defines properties and methods common to every object in the collection. Objects are instances of classes.
  • Method: A function defined in a class.
  • Class variables: Class variables are common across instantiated objects. Class variables are defined within the class and outside the body of the function. 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 the method only apply to the class of the current instance.
  • Instance variable: In the class declaration, attributes are represented by variables, which are called instance variables, and instance variables are variables modified with self.
  • Inheritance: That is, a derived class (derived class) inherits the fields and methods of the base class (base class). Inheritance also allows an object of a derived class to be treated as an object of a base class. 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 concrete object of the class.
  • Object: An instance of a data structure defined by a class. Objects consist of two data members (class variables and instance variables) and methods.

Compared with other programming languages, Python adds a class mechanism 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 can call methods with the same name in the base class.

Objects can contain any amount and type of data.

class definition

The syntax format is as follows:

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

After a class is instantiated, its properties can be used, in fact, after a class is created, its properties can be accessed by the class name.

class object

Class objects support two operations: property reference and instantiation.

Attribute references use the same standard syntax as all attribute references in Python: obj.name.

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

Example (Python 3.0+)

#!/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, where x is an empty object.

The output of executing the above program is:

MyClass 类的属性 i 为: 12345
MyClass 类的方法 f 输出为: hello world

Classes have a special method (constructor) called init () that is called automatically when the class is instantiated, like so:

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

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

x = MyClass()
Of course, the \ init () method can have parameters, which are passed to the instantiation of the class via \ init (). For example:

Example (Python 3.0+)

#!/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 the instance of the class, not the class

Class methods have only one special difference from ordinary functions - they must have an additional first parameter name, which by convention is called self.

class Test:
    def prt(self):
        print(self)
        print(self.__class__)
 
t = Test()
t.prt()
```python
以上实例执行结果为:
```python
<__main__.Test instance at 0x100771878>
__main__.Test

It is obvious from the execution result that self represents the instance of the class and represents the address of the current object, while self.class points to the class.

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

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

The execution result of the above example is:

<__main__.Test instance at 0x100771878>
__main__.Test

class method

Inside the class, use the def keyword to define a method. Different from the general function definition, the class method must contain the parameter self, which is the first parameter, and self represents the instance of the class.

Example (Python 3.0+)

#!/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))
 
# 实例化类
p = people('runoob',10,30)
p.speak()

The output of executing the above program is:

runoob 说:10 岁。

inherit

Python also supports inheritance of classes. If a language does not support inheritance, classes are meaningless. The derived class definition looks like this:

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

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

BaseClassName (the base class name in the instance) must be defined in the same scope as the derived class. Instead of classes, expressions can also be used, which is useful when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName):

Example (Python 3.0+)

#!/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 of executing the above program is:

ken 说:10 岁了,我在读 3 年级

multiple inheritance

Python also has limited support for multiple inheritance forms. The class definition of multiple inheritance is as follows:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>

Pay attention to the order of the parent class in the parentheses. If the parent class has the same method name, but it is not specified when the subclass is used, 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 method is contained in the parent class.

Example (Python 3.0+)

#!/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 of executing the above program is:

我叫 Tim,我是一个演说家,我演讲的主题是 Python

method override

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:

Example (Python 3.0+)

#!/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 of executing the above program is:

调用子类方法
调用父类方法

Class Properties and Methods

class private properties

__private_attrs: At the beginning of two underscores, the attribute is declared private and cannot be used or directly accessed outside the class. When using self.__private_attrs in a method inside a class.

##Methods of a class
Inside a class, use the def keyword to define a method. Different from general function definitions, a class method must contain the parameter self, which is the first parameter, and self represents an instance of the class.

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

##Private method of the class
__private_method: Start with two underscores, declare the method as a private method, which can only be called inside the class, not outside the class. self.__private_methods.

Instance The private attribute instance of the class
is as follows:

Example (Python 3.0+)

#!/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 of executing the above program is:

1
2
2
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    print (counter.__secretCount)  # 报错,实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'

The private method instance of the class is as follows:

Example (Python 3.0+)

#!/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('菜鸟教程', 'www.runoob.com')
x.who()        # 正常输出
x.foo()        # 正常输出
x.__foo()      # 报错

The private method of the class:

  • _ init _ : Constructor, called when an object is created
  • _ del _ : Destructor, used when releasing the object
  • _repr_ : print, convert
  • _ setitem _ : Assign by index
  • _ getitem _: get the value by index
  • _ len _: get the length
  • _ cmp _: comparison operation
  • _ call _: function call
  • _ add _: addition operation
  • _ sub _: Subtraction
  • _mul_ : multiplication operation
  • _truediv_ : division operation
  • _ mod _: remainder operation
  • _pow_ : power

operator overloading

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

Example (Python 3.0+)

#!/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/u011397981/article/details/131099609