Home Backend Development Python Tutorial Python类的专用方法实例分析

Python类的专用方法实例分析

Jun 10, 2016 pm 03:18 PM
python dedicated method kind

本文实例讲述了Python类的专用方法。分享给大家供大家参考。具体分析如下:

Python 类可以定义专用方法,专用方法是在特殊情况下或当使用特别语法时由 Python 替你调用的,而不是在代码中直接调用(象普通的方法那样)。

1. __init__

类似于构造函数

复制代码 代码如下:
#!/usr/local/bin/python
class Study:
        def __init__(self,name=None):
                self.name = name
        def say(self):
                print self.name
study = Study("Badboy")
study.say()
2. __del__

类似于析构函数

复制代码 代码如下:
#!/usr/local/bin/python
class Study:
        def __init__(self,name=None):
                self.name = name
        def __del__(self):
                print "Iamaway,baby!"
        def say(self):
                print self.name
study = Study("zhuzhengjun")
study.say()
3. __repr__

使用repr(obj)的时候,会自动调用__repr__函数,该函数返回对象字符串表达式,
用于重建对象,如果eval_r(repr(obj))会得到一个对象的拷贝。

复制代码 代码如下:
#!/usr/local/bin/python
class Study:
        def __init__(self,name=None):
                self.name = name
        def __del__(self):
                print "Iamaway,baby!"
        def say(self):
                print self.name
        def __repr__(self):
                return "Study('jacky')"
study = Study("zhuzhengjun")
study.say()
print type(repr(Study("zhuzhengjun"))) # str
print type(eval_r(repr(Study("zhuzhengjun")))) # instance
study = eval_r(repr(Study("zhuzhengjun")))
study.say()
4. __str__

Python能用print语句输出内建数据类型。有时,程序员希望定义一个类,要求它的对象也能用print语句输出。Python类可定义特殊方法__str__,为类的对象提供一个不正式的字符串表示。如果类的客户程序包含以下语句:

复制代码 代码如下:
print objectOfClass
那么Python会调用对象的__str__方法,并输出那个方法所返回的字符串。
复制代码 代码如下:
#!/usr/local/bin/python
class PhoneNumber:
        def __init__(self,number):
                 self.areaCode=number[1:4]
                 self.exchange=number[6:9]
                 self.line=number[10:14]
        def __str__(self):
                return "(%s) %s-%s"%(self.areaCode,self.exchange,self.line)
def test():
         newNumber=raw_input("Enter phone number in the form. (123) 456-7890: \n")
         phone=PhoneNumber(newNumber)
         print "The phone number is:"
         print phone
if__name__=="__main__":
         test()

方法__init__接收一个形如"(xxx) xxx-xxxx"的字符串。字符串中的每个x都是电话号码的一个位数。方法对字符串进行分解,并将电话号码的不同部分作为属性存储。
方法__str__是一个特殊方法,它构造并返回PhoneNumber类的一个对象的字符串表示。解析器一旦遇到如下语句:

复制代码 代码如下:
print phone
就会执行以下语句:
复制代码 代码如下:
print phone.__str__()
程序如果将PhoneNumber对象传给内建函数str(如str(phone)),或者为PhoneNumber对象使用字符串格式化运算符%(例如"%s"%phone),Python也会调用__str__方法。
5. __cmp __

比较运算符,0:等于 1:大于 -1:小于

复制代码 代码如下:
class Study:
     def __cmp__(self, other):
         if other > 0 :
             return 1
         elif other              return - 1
         else:
             return 0
study = Study()
if study > -10:print 'ok1'
if study if study == 0:print 'ok3'
打印:ok2 ok3

说明:在对类进行比较时,python自动调用__cmp__方法,如-10

6. __getitem__

__getitem__ 专用方法很简单。象普通的方法 clear,keys 和 values 一样,它只是重定向到字典,返回字典的值。

复制代码 代码如下:
class Zoo:
     def __getitem__(self, key):
         if key == 'dog':return 'dog'
         elif key == 'pig':return  'pig'
         elif key == 'wolf':return 'wolf'
         else:return 'unknown'
zoo = Zoo()
print zoo['dog']
print zoo['pig']
print zoo['wolf']
打印:
dog pig wolf

7. __setitem__

__setitem__ 简单地重定向到真正的字典 self.data ,让它来进行工作。

复制代码 代码如下:
class Zoo:
     def __setitem__(self, key, value):
         print 'key=%s,value=%s' % (key, value)
zoo = Zoo()
zoo['a'] = 'a'
zoo['b'] = 'b'
zoo['c'] = 'c'
打印:
key=a,value=a
key=b,value=b
key=c,value=c

8. __delitem__

__delitem__ 在调用 del instance[key] 时调用,你可能记得它作为从字典中删除单个元素的方法。当你在类实例中使用 del 时,Python 替你调用 __delitem__ 专用方法。

复制代码 代码如下:
class A:
     def __delitem__(self, key):
         print 'delete item:%s' %key
a = A()
del a['key']

希望本文所述对大家的Python程序设计有所帮助。

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

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.

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.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

See all articles