perl-面向对象
我看这个教程,也是觉得有点意思。面向对象一页就将完了?但是仔细去一看,却又无比清晰,我甚至觉得我python面向对象学的有点问题。因为关于实例化一个对象的过程,理解的没有这里深刻。而他仅仅只用了几句话就讲清楚了事物的本质。
所以有必要重新认识一下OOP:
OOP的目的是什么
除了相比于perl中的模块或者python中的函数而言,一个重要的特性是支持:继承,封装,多态,当然perl中的模块也具有封装的特点。可以看出OOP对代码的复用率更高。
Object对象:
我觉得这个解释特别好:
An object is a single entity that combines both data and code. Object is described in the following terms:
- Actions or methods describe what it can do. It is the code part of the object.
- Attributes or properties describe what information the object conveys. It is the data part of the object.
Class类
A class is a blueprint or template of similar objects.
封装继承多态的解释:
Encapsulation
Through object, you can hide its complexity which is known as abstraction or encapsulation in object oriented programming. It means the client of the object does not need to care about the internal logic of the object but still can use the object through its interfaces (methods).
Inheritance
Inheritance means one class inherits both attributes and methods from another class. Inheritance enables you to reuse and extend existing classes without copy-n-paste the code or re-invent the wheel.
- A class that other classes inherit from is called base class or superclass.
- A class that inherits from other class called subclass or derived class.
Polymorphism
Polymorphism means “many forms*” in *Greek. It means a method call can behave differently depending on the type of the object that calls it.
以上属于通用oop的理解。下面是perl中的oop。
perl中的oop
这里对象的解释一语道破类与对象的本质区别。类只是一个框架模板,而对象则是一个reference,一个内存地址,就是为了知道它是属于那个类的。
Perl OOP rules
可以看出从结构上与module差别不是很大。
There are three important rules in Perl object oriented programming:
- A class is a package.
- An object is a reference that knows its class.
- A method is a subroutine.
定义perl的class
在perl中class指的就是一个package,和模块一样。
- 选定好一个class的名字:
Product
- 新建文件:
Product.pm
1 | package Product; |
构建perl的object
这里与python差别可是有点大。perl中使用一个子程序、函数来构建object。一般来说我们会使用new
作为函数的名称,比较容易辨别。当然了其它任何名字都是可以的。
1 | sub new{ |
和模块不同,每当我们调用
new()
方法的时候,perl就会自动的将类的名字Product
作为第一个参数传入到了特殊变量@_
中。当我们创建一个object时,实际上是创建了一个reference,告诉它属于那个类。而内建的函数
bless
就是用来创建一个类的reference,同时返回一个类的实例。bless()
函数的语法:1
object = bless reference, classname;
We’ve passed a hash reference to the
bless()
function. You can pass any kind of reference to the bless function e.g., array reference, however, it is much easier to work with a hash reference.
调用这个Product类
1 | #!/usr/bin/perl |
We called the method new()
of the Product
class and get an object $iphone
. We passed a hash reference to the new()
method containing serial
, name
and price
.
完整的事例
定义一个Product类
1 | package Product; |
使用Product类
1 | #!/usr/bin/perl |
这里还是有许多不是很明白的地方,以后边用边加深理解。
另外我安装了一个atom,因为我的vim总感觉缺点啥,可能是没有自动补全吧。没有安装sublime是因为在windows上老是弹出需要购买的信息。看着不是很舒服