search
HomeBackend DevelopmentPython TutorialPython类的专用方法实例分析

本文实例讲述了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
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: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.