Python Object-Oriented Programming - Elementary

王林
Release: 2023-04-11 23:58:05
forward
1913 people have browsed it

Preface

Object-oriented: Using the concept of objects (entities) to build models and simulate the objective world to analyze, design, and implement software. Object-oriented Programming (OOP for short) is a design and programming method that solves software reuse. It describes similar operation logic and operation application data and status in the software system in the form of classes and objects. The form of examples is reused in the software system to improve software development efficiency.

Object-oriented programming is an extremely important concept in Python.

1. Object-oriented and process-oriented

1. Two types of software development and design methods

  1. Process-oriented programming: From top to bottom according to business logic, the needs will be The functional codes used are encapsulated into functions, focusing on the steps and processes of development. The typical code is C language (focusing on the process)
  2. Object-oriented programming: Classify and encapsulate functions or required functions, focusing on Pay attention to which specific class and function implements the function. Typical codes are Java, C and other languages ​​(pay attention to the results)

2. Object-oriented related terms

  • Class (Class) : Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. The object is an instance of a class.
  • Instance: also called object. Through the initialization method defined by the class, it is given a specific value and becomes a "flesh and blood entity".
  • 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, used to process 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 act on 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 and are declared inside the class declaration but outside other member methods of the class.
  • Method: Function defined in the class.
  • 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 (override), also called method rewriting.
  • Static method: A method that can be executed by a class without instantiation.
  • Class method: A class method is a method that operates on the class itself as an object.

Three major characteristics of object-oriented:

  • Encapsulation: Wrap the internal implementation, make it transparent to the outside, and provide a mechanism for calling the API interface.
  • Inheritance: That is, a derived class inherits the variables and methods of the parent class (base class).
  • Polymorphism: Processed in different ways depending on the object type.

2. Classes and Objects

1. Objects

Objects are the core of object-oriented programming. In the process of using objects, in order to have common characteristics and behaviors A set of abstract definitions of objects, forming a class

2. Class

1) Concept

A class is a type of thing, and the object is the specific implementation of this type of thing. Classes have the same attributes and behaviors

2) The composition of a class

  • Class name: the name of the class
  • Attributes: characteristics of things
  • Method: What to do specifically

3) Abstract

Objects with the same or similar attributes and behaviors can be abstracted into a class

4) Class Classification

To create a class, use the class keyword, add the class name, and then add parentheses, with object in the parentheses. Such a class is called a new-style class; it can also be without parentheses and object in parentheses. Such classes are called: classic classes.

# 新式类 
class Meeting2(object): 
pass 
# 经典类 
class Meeting2: 
pass
Copy after login

5) Create object

A = Meeting1() 
B
Copy after login

6) self

The first parameter of the class method must be self (by convention it is self, it can also be other names), It is not necessary to pass it in when calling. self represents an instance of a class

3. Get or add object attributes

There is a class named meeting as follows, in which attributes such as name, age, sex, address, and attack are initialized. Define There are two methods introduction and attacked:

class Meeting(object):
"""meeting类的类描述"""

def __init__(self, name, age, sex, address, attack):
"""构造函数"""
self.name = name
self.age = int(age)
self.sex = sex
self.address = address
self.attack = int(attack)

def introduction(self):
print("姓名:{}".format(self.name))
print("年龄:{}".format(self.age))
print("性别:{}".format(self.sex))
print("地址:{}".format(self.address))

def attacked(self):
print(f"{self.name}正在向您发起攻击,攻击力为{self.attack}!")

def foreign_fun():
print("我是外部函数")
Copy after login

1.hasattr-check whether the object contains the specified attribute or method

Usage:

hasattr(object,name)

Function: Check whether the object contains the specified attribute or method

Return value: Returns true if it exists, false if it does not exist

# 实例化meeting类
Meeting = Meeting("张三", 20, "男", "南京", 108)

# 获取Meeting对象中是否存在name属性
print(hasattr(Meeting, "name"))# True
# 获取Meeting对象中是否存在mobile属性
print(hasattr(Meeting, "mobile"))# False
# 获取Meeting对象中是否存在attacked方法
print(hasattr(Meeting, "attacked"))# True
Copy after login

2.getattr-Get the attribute value of the specified attribute in the object

Usage:

getattr(object,name[,default])

Function: Get the attribute value of the specified attribute in the object

Return value: If If it exists, the attribute value of the attribute is returned; if it does not exist, the specified content is returned

# 实例化meeting类
Meeting = Meeting("张三", 20, "男", "南京", 108)

# 获取Meeting对象中name属性的属性值
print(getattr(Meeting, "name"))# 张三
# 获取Meeting对象中kills属性或方法的值,若不存在则返回指定内容
print(getattr(Meeting, "kills", "未找到kills方法或属性"))# 未找到kills方法或属性
# 获取Meeting对象中attacked方法,返回值为函数地址
print(getattr(Meeting, "attacked"))
# 使用getattr方法可以直接调用Meeting对象中的方法
f = getattr(Meeting, "attacked")
f()
Copy after login

The printing result is as follows:

Python Object-Oriented Programming - Elementary

3.setattr-为object对象的name属性设置指定value

用法:

setattr(object,name,value)

作用:为object对象的指定属性设置指定value

返回值:

# 实例化meeting类
Meeting = Meeting("张三", 20, "男", "南京", 108)

# 将对象中name属性的值改为“刘德华”
setattr(Meeting, "name", "刘德华")
# 获取对象中name的属性值
print(getattr(Meeting, "name"))# 刘德华
# 将对象外部的名为foreign_fun的方法引入对象内部,并重新命名为“new_foreign_fun”
setattr(Meeting, "new_foreign_fun", foreign_fun)
# 获取对象中是否存在foreign_fun的属性或方法,返回值为True或False
print(hasattr(Meeting, "foreign_fun"))# False
# 获取对象中是否存在new_foreign_fun的属性或方法,返回值为True或False
print(hasattr(Meeting, "new_foreign_fun"))# True
Copy after login

打印结果如下:

Python Object-Oriented Programming - Elementary

四、魔法方法

1.__init__() 构造函数

__init__()方法是Python中一种特殊的方法,被称为构造函数或初始化方法,当创建这个类的实例时就会调用该方法。

class Meeting(object):
"""meeting类的类描述"""

def __init__(self, name, age, sex, address, attack):
"""构造函数"""
self.name = name
self.age = int(age)
self.sex = sex
self.address = address
self.attack = int(attack)

C = Meeting("张三", 20, "男", "南京", 108)
print(C.name)# 张三
print(C.address)# 南京
Copy after login

2.__del__() 析构函数

当删除对象时,Python解释器会默认调用一个方法__del__(),相当于unittest框架中的tearDown()函数

def __del__(self): 
"""析构函数""" 
print("%s攻击结束" % (self.name)) 
Copy after login

每调用一次对象,都会执行一次__del__()方法

Python Object-Oriented Programming - Elementary

3.引用计数

D = Meeting("张三", 20, "男", "南京", 108)
# 计算当前实例引用计数,D引用一次,sys.getrefcount(D)引用一次
print(sys.getrefcount(D))# 2
Copy after login

D对象的引用计数为2次,一次是D引用,一次是sys.getrefcount所引用的

4.__str()__字符串函数

__str__方法需要返回一个字符串,当做这个对象的描述信息,当使用print输出对象的时候,只要定义了__str__(self)方法,那么就会打印这个方法返回的数据

def __str__(self):
"""字符串函数"""
return "我是Meeting类的字符串描述"
# __str__():字符串函数,定义__str__()方法时,打印对象,打印的是__str__()方法的返回值,否则打印类的内存地址
print(D)# 我是Meeting类的字符串描述
Copy after login
  • 未定义__str__()方法时,打印对象,打印的是Meeting类的内存地址:<__main__.Meeting object at0x014A7748>
  • 定义了__str__()方法后,打印对象,打印的是__str__()方法的返回值:我是Meeting类的字符串描述

五、Python的内置属性

1.__dict__:获取类的属性

获取类的属性,包含一个字典,由类的数据属性组成

# __dict__:获取类的属性,返回值为字典类型 
print(D.__dict__) 
# {'name': '张三', 'age': 20, 'sex': '男', 'address': '南京', 'attack': 108} 
Copy after login

2.__doc__:获取类的文档字符串

class Meeting(object): 
 """meeting1类的类描述""" 
 
# __doc__:获取类的文档字符串 
print(D.__doc__) # meeting1类的类描述 
Copy after login

3.__name__:获取类名

# __name__:获取类名 
print(Meeting.__name__) # Meeting 
Copy after login

4.__module__:类定义所在的模块

类的全名是'__main__.clssName',如果类位于一个导入模块mymod中,那么className.__module__等于mymod

from common.http_requests import HttpRequests
# __module__:类定义所在的模块
print(Meeting.__module__)# __main__
print(HttpRequests.__module__)# common.http_requests
Copy after login

Meeting类的路径为__main__,而从common文件的http_requests文件中导入了HttpRequests类,打印其路径,则为common.http_requests

5.__bases__:获取类的所有父类构成元素

获取类的所有父类构成元素(包含了一个由所有父类元素组成的元组)。例如下面有一个Song类,其继承了父类Music,则获取到的Song类的所有父类构成元素为:(,)

class Music(object):
pass

class Song(Music):
pass

print(Song.__bases__)# (<class '__main__.Music'>,)
Copy after login

小结

本篇文章我们介绍了面向对象的相关概念,下面来简单总结一下:

面向对象相关概念:

  • 类和对象:类是一类事物,对象即是这一类事物的具体实现,类具有相同的属性和行为;
  • 类的组成:类名、属性、方法
  • 带object的为新式类,不带object的为经典类

获取或添加对象属性:

  • hasattr:检查对象是否包含指定属性或方法
  • getattr:获取对象中指定属性的属性值
  • setattr:为object对象的name属性设置指定value

魔法方法:

  • __init__() 构造函数:又叫初始化方法,用来初始化一些成员变量
  • __del__() 析构函数:每调用一次对象,都会执行一次__del__()方法,相当于Unittest框架中的tearDown
  • __str()__字符串函数:返回一个字符串,当做这个对象的描述信息

Python内置属性:

  • __dict__:获取类的属性,返回值为字典类型
  • __doc__:获取类的文档字符串
  • __name__:获取类名
  • __module__:类定义所在的模块
  • __bases__:获取类的所有父类构成元素,返回类型为元组

The above is the detailed content of Python Object-Oriented Programming - Elementary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template