python序列文章之python方法链

[复制链接]
璀璨星辰 发表于 2017-12-31 09:37:28 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
% d) q/ _3 S4 K$ s
对python感兴趣的小伙伴可加群:526929231,大量学习资料在群文件里,欢迎大家加入
* o( V' b  P3 {0 _$ D/ D) m/ _, h+ d写这篇文章来由,有朋友说下面这样的代码看不懂。- d5 Y. R7 S" r; p7 E! u2 D" @

8 ~5 b) _6 L) zchoice = raw_input("please input:\n").strip()[0].lower()
- p# \* d" a4 E! u: ^/ m& C8 e* E很多对于有经验的程序员来说,这些都不是事,2 ^. f7 W0 P" V  j5 B! ?
但对于初学者来说,看到这样的语法头有点大。
! A* n9 h9 O6 G6 t' `这个其实是面向对象中方法链的概念。
0 Z( c& v# P1 }4 c; T. Z  e0 R请看维基百科上Method chaining的定义
# Y; I, S9 N5 b- q: ?7 C& k# G$ _ Method chaining, also known as named parameter idiom,  is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring  variables to store the intermediate results. Local variable declarations are syntactic  sugar because of the difficulty humans have with deeply nested method calls. A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.具体在python中,请看小编的分析:
1 ~; f6 o: t2 ~9 P- j! O: I( j8 E8 o# _
有的python初学者对python方法连续调用不是很清楚,像雾里看花一样。python一切都是对象,对象调用它的方法,如果带返回值,返回值也是对象, 这个返回值也有方法,当然就可以用点号调用它的方法, 如此下去,就是python方法链调用也。如何设计方法链python代码
7 @- K; |  B& R9 q0 T
! R( }; W$ K8 _class Person(object): """方法链小sample""" def name(self, value): self.name = value return self # 返回实例对象自己才能再调用实例对象的方法。 def work(self, value): self.working = value return self def introduce(self): print "你好, 我的名字:", self.name, ",我的工作:", self.working, ",教初学者学会编程!"person = Person()person.name("小编").work("python").introduce()php方法链代码* z7 X7 J4 N% ]2 V2 }

) L3 {* D, f3 f) P6 e class Person{ public $name; public $working; public function setName($value){ $this->name = $value; return $this; } public function work($value){ $this->working = $value; return $this; } public function introduce(){ echo "你好, 我的名字:".$this->name.",我的工作:".$this->working.",教初学者学会编程!\n"; } } $person = new Person(); $person->setName("小编")->work("php")->introduce();

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

发布主题
推荐阅读更多+
阅读排行更多+
用心服务创业者
0851-88611148
周一至周五 9:00-18:00
意见反馈:admin@0851life.com

扫一扫关注我们

Powered by 童码少儿编程 X3.4© 2001-2013 0851life Inc.|网站地图