📄 ch13_12.htm
字号:
<HTML><HEAD><TITLE>Recipe 13.11. Generating Attribute Methods Using AUTOLOAD (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen & Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly & Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:42:27Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch13_01.htm"TITLE="13. Classes, Objects, and Ties"><LINKREL="prev"HREF="ch13_11.htm"TITLE="13.10. Accessing Overridden Methods"><LINKREL="next"HREF="ch13_13.htm"TITLE="13.12. Solving the Data Inheritance Problem"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_11.htm"TITLE="13.10. Accessing Overridden Methods"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 13.10. Accessing Overridden Methods"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch13_01.htm"TITLE="13. Classes, Objects, and Ties"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_13.htm"TITLE="13.12. Solving the Data Inheritance Problem"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 13.12. Solving the Data Inheritance Problem"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch13-39267">13.11. Generating Attribute Methods Using AUTOLOAD</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-pgfId-1353">Problem<ACLASS="indexterm"NAME="ch13-idx-1000004584-0"></A><ACLASS="indexterm"NAME="ch13-idx-1000004584-1"></A><ACLASS="indexterm"NAME="ch13-idx-1000004584-2"></A></A></H3><PCLASS="para">Your object needs accessor methods to set or get its data fields, and you're tired of writing them all out one at a time.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-pgfId-1359">Solution</A></H3><PCLASS="para">Carefully use Perl's AUTOLOAD mechanism as a proxy method generator so you don't have to create them all yourself each time you want to add a new data field.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-pgfId-1365">Discussion</A></H3><PCLASS="para">Perl's AUTOLOAD mechanism intercepts all possible undefined method calls. So as not to permit arbitrary data names, we'll store the list of permitted fields in a hash. The AUTOLOAD method will check to verify that the accessed field is in that hash.</P><PRECLASS="programlisting">package Person;use strict;use Carp;use vars qw($AUTOLOAD %ok_field);# Authorize four attribute fieldsfor my $attr ( qw(name age peers parent) ) { $ok_field{$attr}++; } sub AUTOLOAD { my $self = shift; my $attr = $AUTOLOAD; $attr =~ s/.*:://; return unless $attr =~ /[^A-Z]/; # skip DESTROY and all-cap methods croak "invalid attribute method: -><CODECLASS="literal">$attr()"</CODE> unless $ok_field{$attr}; $self->{uc $attr} = shift if @_; return $self->{uc $attr};}sub new { my $proto = shift; my $class = ref($proto) || $proto; my $parent = ref($proto) && $proto; my $self = {}; bless($self, $class); $self->parent($parent); return $self;} 1;</PRE><PCLASS="para">This class supports a constructor named <CODECLASS="literal">new</CODE>, and four attribute methods: <CODECLASS="literal">name</CODE>, <CODECLASS="literal">age</CODE>, <CODECLASS="literal">peers</CODE>, and <CODECLASS="literal">parent</CODE>. Use the module this way:</P><PRECLASS="programlisting">use Person;my ($dad, $kid);$dad = Person->new;$dad->name("Jason");$dad->age(23);$kid = $dad->new;$kid->name("Rachel");$kid->age(2);printf "Kid's parent is %s\n", $kid->parent->name;<CODECLASS="userinput"><B><CODECLASS="replaceable"><I>Kid's parent is Jason</I></CODE></B></CODE></PRE><PCLASS="para">This is tricky when producing inheritance trees. Suppose you'd like an Employee class that had every data attribute of the Person class, plus two new ones, like <CODECLASS="literal">salary</CODE> and <CODECLASS="literal">boss</CODE>. Class Employee can't rely upon an inherited <CODECLASS="literal">Person::AUTOLOAD</CODE> to determine what Employee's attribute methods are. So each class would need its own <CODECLASS="literal">AUTOLOAD</CODE> function. This would check just that class's known attribute fields, but instead of croaking when incorrectly triggered, it would call its overridden superclass version.</P><PCLASS="para">Here's a version that takes this into consideration:</P><PRECLASS="programlisting">sub AUTOLOAD { my $self = shift; my $attr = $AUTOLOAD; $attr =~ s/.*:://; return if $attr eq 'DESTROY'; if ($ok_field{$attr}) { $self->{uc $attr} = shift if @_; return $self->{uc $attr}; } else { my $superior = "SUPER::$attr"; $self->$superior(@_); } }</PRE><PCLASS="para">If the attribute isn't in our OK list, we'll pass it up to our superior, hoping that it can cope with it. But you can't inherit this <CODECLASS="literal">AUTOLOAD</CODE>; each class has to have its own, because it is unwisely accessing class data directly, not through the object. Even worse, if a class A inherits from two classes B and C, both of which define their own <CODECLASS="literal">AUTOLOAD</CODE>, an undefined method call on A will hit the <CODECLASS="literal">AUTOLOAD</CODE> in only one of the two parent classes.</P><PCLASS="para">We could try to cope with these limitations, but <CODECLASS="literal">AUTOLOAD</CODE> eventually begins to feel like a kludge piled on a hack piled on a workaround. There are better approaches for the more complex situations.<ACLASS="indexterm"NAME="ch13-idx-1000004594-0"></A><ACLASS="indexterm"NAME="ch13-idx-1000004594-1"></A><ACLASS="indexterm"NAME="ch13-idx-1000004594-2"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-pgfId-1485">See Also</A></H3><PCLASS="para">The examples using AUTOLOAD in <ICLASS="filename">perltoot </I>(1); <ACLASS="olink"HREF="../prog/ch05_01.htm">Chapter 5</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; <ACLASS="xref"HREF="ch10_16.htm"TITLE="Trapping Undefined Function Calls with AUTOLOAD">Recipe 10.15</A>; <ACLASS="xref"HREF="ch13_13.htm"TITLE="Solving the Data Inheritance Problem">Recipe 13.12</A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_11.htm"TITLE="13.10. Accessing Overridden Methods"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 13.10. Accessing Overridden Methods"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_13.htm"TITLE="13.12. Solving the Data Inheritance Problem"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 13.12. Solving the Data Inheritance Problem"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">13.10. Accessing Overridden Methods</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">13.12. Solving the Data Inheritance Problem</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright © 2002</a> O'Reilly & Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -