Python类的专用方法实例分析
本文实例讲述了Python类的专用方法。分享给大家供大家参考。具体分析如下:
Python 类可以定义专用方法,专用方法是在特殊情况下或当使用特别语法时由 Python 替你调用的,而不是在代码中直接调用(象普通的方法那样)。
1. __init__
类似于构造函数
class Study:
def __init__(self,name=None):
self.name = name
def say(self):
print self.name
study = Study("Badboy")
study.say()
2. __del__
类似于析构函数
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))会得到一个对象的拷贝。
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__,为类的对象提供一个不正式的字符串表示。如果类的客户程序包含以下语句:
那么Python会调用对象的__str__方法,并输出那个方法所返回的字符串。
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类的一个对象的字符串表示。解析器一旦遇到如下语句:
就会执行以下语句:
程序如果将PhoneNumber对象传给内建函数str(如str(phone)),或者为PhoneNumber对象使用字符串格式化运算符%(例如"%s"%phone),Python也会调用__str__方法。
5. __cmp __
比较运算符,0:等于 1:大于 -1:小于
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 一样,它只是重定向到字典,返回字典的值。
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 ,让它来进行工作。
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__ 专用方法。
def __delitem__(self, key):
print 'delete item:%s' %key
a = A()
del a['key']
希望本文所述对大家的Python程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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.

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.

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.

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.

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.

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.

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.
