Home Backend Development Python Tutorial Describe the details of object-oriented python code

Describe the details of object-oriented python code

May 10, 2017 am 11:38 AM

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
Copy after login

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("未绑定方法对象,需要传递一个实例") # 错误的调用
Copy after login

类属性与实例属性

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

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

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

私有化

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
Copy after login

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;}
Copy after login

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

字典会占据大量内存,如果你有一个属性数量很少的类,但有很多实例,那么正好是这种情况。为内存上的考虑,可以使用 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;
Copy after login


这种特性的主要目的是节约内存。其副作用是某种类型的"安全",它能防止用户随心所欲的动态增加实例属性。带 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 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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles