Home Backend Development Python Tutorial Python中方法链的使用方法

Python中方法链的使用方法

Jun 10, 2016 pm 03:06 PM
python

方法链(method chaining)是面向对象的编程语言中的一种常见语法,可以让开发者在只引用对象一次的情况下,对同一个对象进行多次方法调用。举个例子:

假设我们有一个Foo类,其中包含有两个方法——bar和baz。

我们创建一个Foo类的实例:

foo = Foo()
Copy after login

如果不使用方法链,要想连续调用对象foo的bar和baz方法的话,我们得这样做:

foo.bar() # Call method bar() on object foo.
foo.baz() # Call method baz() on object foo.
Copy after login

如果使用方法链的话,我们就能这样实现: foo.bar().baz()

方法链的一个好处,是可以减少你使用对象名的次数。调用的方法越多,能够减少的次数就越多。因此,这个方法也能一定程度上减少需要阅读、测试、调试、维护的代码数量。这个好处不大,但也是有用的。

请注意,方法链的一个限制是,只能用在不需要返回其他值的方法上,因为你需要返回self对象。即使Python支持用一个return语句返回多个值,也可能无法解决这个问题。

下面是在Python中实现方法链的一个示例:

class Person:
  def name(self, value):
    self.name = value
    return self

  def age(self, value):
    self.age = value
    return self

  def introduce(self):
    print "Hello, my name is", self.name, "and I am", self.age, "years old."

person = Person()
person.name("EarlGrey").age(21).introduce()
# => Hello, my name is EarlGrey and I am 21 years old.

Copy after login

上面那种实现可能太简单了。下面我们来看一种更加现实的方法链使用方法:编写一个字符串处理程序string_processor.py,支持方法链。

import copy

class StringProcessor(object):
  '''
  A class to process strings in various ways.
  '''
  def __init__(self, st):
    '''Pass a string for st'''
    self._st = st

  def lowercase(self):
    '''Make lowercase'''
    self._st = self._st.lower()
    return self

  def uppercase(self):
    '''Make uppercase'''
    self._st = self._st.upper()
    return self

  def capitalize(self):
    '''Make first char capital (if letter); make other letters lower'''
    self._st = self._st.capitalize()
    return self

  def delspace(self):
    '''Delete spaces'''
    self._st = self._st.replace(' ', '')
    return self

  def rep(self):
    '''Like Python's repr'''
    return self._st

  def dup(self):
    '''Duplicate the object'''
    return copy.deepcopy(self)

def process_string(s):
  print
  sp = StringProcessor(s)
  print 'Original:', sp.rep()
  print 'After uppercase:', sp.dup().uppercase().rep()
  print 'After lowercase:', sp.dup().lowercase().rep()
  print 'After uppercase then capitalize:', sp.dup().uppercase().\
  capitalize().rep()
  print 'After delspace:', sp.dup().delspace().rep()

def main():
  print "Demo of method chaining in Python:"
  # Use extra spaces between words to show effect of delspace.
  process_string('hOWz It   GoInG?')
  process_string('The   QUIck  brOWn     fOx')

main()

Copy after login

下面是这个程序的运行结果:

$ python string_processor.py

Original: hOWz It   GoInG?
After uppercase: HOWZ IT   GOING?
After lowercase: howz it   going?
After uppercase then capitalize: Howz it   going?
After delspace: hOWzItGoInG?

Original: The   QUIck  brOWn     fOx
After uppercase: THE   QUICK  BROWN     FOX
After lowercase: the   quick  brown     fox
After uppercase then capitalize: The   quick  brown     fox
After delspace: TheQUIckbrOWnfOx

Copy after login

综上,我们可以发现,方法链有其用处,不过过度使用可能不太好。

如何在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.

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.

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.

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.

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.

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.

See all articles