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

Describe the details of object-oriented python code

Y2J
Release: 2017-05-10 11:38:50
Original
1245 people have browsed it

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!

Related labels:
source:php.cn
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