search
HomeBackend DevelopmentPython TutorialDescribe the details of object-oriented python code

Python has been an object-oriented language from the beginning. Because of this, it is easy to create classes and objects in Python. The following article will introduce you to the knowledge points about Python object-oriented programming in detail. Friends in need can refer to it. Let’s take a look together.

Preface

If you have not been exposed to object-oriented programming languages before, you may need to know something first Some basic features of object-oriented languages ​​form a basic object-oriented concept in your mind, which will help you learn Python object-oriented programming more easily.

Next let’s learn about the knowledge points about Python object-oriented programming.

Classes and Instances

The class is the definition of the object, and the instance is the "real object", which stores the objects defined in the class Object specific information.

Classes, Properties and methodsNaming convention

Class names usually start with a capital letter. This is standard convention and can help you identify classes, especially during instantiation (sometimes looking like function calls). Also, data attributes (variables or constants) should sound like names of data values, and method names should indicate the behavior of the corresponding object or value.

Another way to express it is: data values ​​should use nouns as names, and methods should use predicates (verbs plus objects). The data item is the object to be operated on, and the method should indicate what operation the programmer wants to perform on the object.

In the defined class, roughly follow this guideline, with data values ​​like "name", "phone" and "email" and behaviors such as "updatePhone" and "updateEmail". This is often called "mixedCase" or "camelCase". The Python specification recommends using camel notation with underscores, for example, "update_phone", "update_email". Classes should also be named carefully, such as "AddrBookEntry", "RepairShop", etc. are good names.

class AddrBookEntry(object):

 def init(self, name, phone, email):
 self.name = name
 self.phone = phone
 self.email = email

 def update_phone(self, phone):
 self.phone = phone

 def update_email(self. email):
 self.email = email

New-style classes and old-style classes

The biggest difference between new-style classes and classic class declarations is that all new-style classes must inheritAt least one parent class. If there is no class to inherit from, the object class can be inherited. Object is the "mother of all classes" and is located at the top of all class inheritance structures. If there is no direct or indirect subclassing of an object, then a classic class is defined. That is, if a parent class is not specified, or if the base class being subclassed has no parent class, a classic class is created.

Classes defined in Python3 are new-style classes by default. To define a new-style class in Python2, you must inherit object or inherit a new-style class.

self variable

#The methods of the class have only one special difference from ordinary functions, that is, they must have an extra first parameter name, but you don't have to assign a value to this parameter when calling this method, Python will provide this value. This particular variable refers to the object itself, and by convention its name is self. Although you can give this parameter any name, it is strongly recommended to use the name self, and other names are deprecated.

init() method

init() is similar to a class constructor, but is not actually a constructor device. After Python creates an instance, during the instantiation process, the init() method is called. When a class is instantiated, additional behaviors can be defined, such as setting initial values ​​or running some preliminary diagnostic code. , which is mainly to perform certain tasks or settings after the instance is created and before the instantiation call returns the instance.

Bound and unbound methods

In Python, methods to access a class can be accessed directly through instances or directly through classes. However, Python strictly requires that methods cannot be called without an instance. This restriction is what Python describes as binding, where a method must be bound (to an instance) in order to be called directly. Unbound methods may be called, but the instance object must be explicitly given to ensure that the call is successful. However, whether bound or not, methods are inherent properties of the class in which they are found, even though they are almost always called through instances. Class methods in Python are also objects. It can be simply understood that methods accessed directly through classes are called "unbound methods", while methods accessed through instances are called "bound methods":

1. Unbound Certain class method: no self

通过类来引用方法返回一个未绑定方法对象。要调用它,你必须显示地提供一个实例作为第一个参数。

2. 绑定的实例方法:有 self

通过实例访问方法返回一个绑定的方法对象。Python 自动地给方法绑定一个实例,所以我们调用它时不用再传一个实例参数。

示例:

class Test:
 def func(self, message):
 print message

object1 = Test()
x = object1.func
x("绑定方法对象,实例是隐藏的")

t = Test.func
t(object1, "未绑定方法对象,需要传递一个实例")
# t("未绑定方法对象,需要传递一个实例") # 错误的调用

类属性与实例属性

类属性仅是与类相关的数据值,和实例属性不同,类属性和实例无关。这些值像静态成员那样被引用,即使在多次实例化中调用类,它们的值都保持不变。不管如何,静态成员不会因为实例而改变它们的值,除非实例中显式改变它们的值。 实例属性与类属性的比较,类似于自动变量和静态变量,但这只是笼统的类推。在你对自动变量和静态变量还不是很熟的情况下,不要深究这些。

类和实例都是名字空间。类是类属性的名字空间,实例则是实例属性的。

可采用类来访问类属性,如果实例没有同名的属性的话,也可以用实例来访问。

私有化

Python并不直接支持私有方式,而要靠程序员自己把握在外部进行特性修改的时机。

为了让方法或者特性变为私有(从外部无法访问),只要在它的名字前面加上双下划线即可。由双下划线  开始的属性在运行时被“混淆”,所以直接访问是不允许的。

实际上,在 Python 带有双下划线的属性或方法并非正真意义上的私有,它们仍然可以被访问。在类的内部定义中,所有以双下划线开始的名字都被“翻译”成前面加上单下划线和类名的形式:

>>> class TestObj(object):
... war = "world"
... 
... def init(self):
...  self.har = "hello"
...  
... def foo(self):
...  print(self.har + self.war)
...  
... 
... 
>>> t = TestObj()
>>> dir(t)
['_TestObjfoo', '_TestObjhar', '_TestObjwar', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getat
tribute', 'gt', 'hash', 'init', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr
', 'sizeof', 'str', 'subclasshook', 'weakref']
>>> t.war
Traceback (most recent call last):
 File "<input>", line 1, in <module>
 t.war
AttributeError: &#39;TestObj&#39; object has no attribute &#39;war&#39;
>>> t.har
Traceback (most recent call last):
 File "<input>", line 1, in <module>
 t.har
AttributeError: &#39;TestObj&#39; object has no attribute &#39;har&#39;
>>> t.foo()
Traceback (most recent call last):
 File "<input>", line 1, in <module>
 t.foo()
AttributeError: &#39;TestObj&#39; object has no attribute &#39;foo&#39;
>>> t._TestObjwar
&#39;world&#39;
>>> t._TestObjhar
&#39;hello&#39;
>>> t._TestObjfoo()
helloworld

slots 类属性

正常情况下,当我们定义了一个 class,创建了一个 class 的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。在 Python 中默认用字典来存储实例的属性。

示例:

>>> class A():
... pass
... 
>>> a = A()
>>> a.name = "huoty"
>>> a.age = 25
>>> print a.name
huoty
>>> print a.age
25
>>> a.dict
{&#39;age&#39;: 25, &#39;name&#39;: &#39;huoty&#39;}

字典位于实例的“心脏” 。 dict属性跟踪所有实例属性。举例来说,你有一个实例 inst,它有一个属性 foo,那使用 inst.foo 来访问它与使用 inst.dict['foo'] 来访问是一致的。

字典会占据大量内存,如果你有一个属性数量很少的类,但有很多实例,那么正好是这种情况。为内存上的考虑,可以使用 slots 属性来替代 dict

slots 是新式类的特性。基本上, slots 是一个类变量,由一序列对象组成,由所有合法标识构成的实例属性的集合来表示。它可以是一个列表,元组或可迭代对象。也可以是标识实例能拥有的唯一的属性的简单字符串。任何试图创建一个其名不在 slots 中的名字的实例属性都将导致 AttributeError 异常:

>>> class SlotedClass(object):
... slots = ("foo", "bar")
... 
... 
>>> c = SlotedClass()
>>> c.foo = 42
>>> c.bar = "hello"
>>> c.goo = "don&#39;t think so"
Traceback (most recent call last):
 File "<input>", line 1, in <module>
AttributeError: &#39;SlotedClass&#39; object has no attribute &#39;goo&#39;


这种特性的主要目的是节约内存。其副作用是某种类型的"安全",它能防止用户随心所欲的动态增加实例属性。带 slots 属性的类定义不会存在 dict 了(除非你在 slots 中增加 dict 元素)。

总结

【相关推荐】

1. Python免费视频教程

2. python遇见数据采集视频

3. Python学习手册

The above is the detailed content of Describe the details of object-oriented python code. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment