Home > Article > Backend Development > Python Object-Oriented Programming - Elementary
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.
Three major characteristics of object-oriented:
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
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
Objects with the same or similar attributes and behaviors can be abstracted into a class
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
A = Meeting1() B
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
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("我是外部函数")
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
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()
The printing result is as follows:
用法:
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
打印结果如下:
__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)# 南京
当删除对象时,Python解释器会默认调用一个方法__del__(),相当于unittest框架中的tearDown()函数
def __del__(self): """析构函数""" print("%s攻击结束" % (self.name))
每调用一次对象,都会执行一次__del__()方法
D = Meeting("张三", 20, "男", "南京", 108) # 计算当前实例引用计数,D引用一次,sys.getrefcount(D)引用一次 print(sys.getrefcount(D))# 2
D对象的引用计数为2次,一次是D引用,一次是sys.getrefcount所引用的
__str__方法需要返回一个字符串,当做这个对象的描述信息,当使用print输出对象的时候,只要定义了__str__(self)方法,那么就会打印这个方法返回的数据
def __str__(self): """字符串函数""" return "我是Meeting类的字符串描述" # __str__():字符串函数,定义__str__()方法时,打印对象,打印的是__str__()方法的返回值,否则打印类的内存地址 print(D)# 我是Meeting类的字符串描述
获取类的属性,包含一个字典,由类的数据属性组成
# __dict__:获取类的属性,返回值为字典类型 print(D.__dict__) # {'name': '张三', 'age': 20, 'sex': '男', 'address': '南京', 'attack': 108}
class Meeting(object): """meeting1类的类描述""" # __doc__:获取类的文档字符串 print(D.__doc__) # meeting1类的类描述
# __name__:获取类名 print(Meeting.__name__) # Meeting
类的全名是'__main__.clssName',如果类位于一个导入模块mymod中,那么className.__module__等于mymod
from common.http_requests import HttpRequests # __module__:类定义所在的模块 print(Meeting.__module__)# __main__ print(HttpRequests.__module__)# common.http_requests
Meeting类的路径为__main__,而从common文件的http_requests文件中导入了HttpRequests类,打印其路径,则为common.http_requests
获取类的所有父类构成元素(包含了一个由所有父类元素组成的元组)。例如下面有一个Song类,其继承了父类Music,则获取到的Song类的所有父类构成元素为:(
class Music(object): pass class Song(Music): pass print(Song.__bases__)# (<class '__main__.Music'>,)
本篇文章我们介绍了面向对象的相关概念,下面来简单总结一下:
面向对象相关概念:
获取或添加对象属性:
魔法方法:
Python内置属性:
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!