【4858.com】Python数据类型及其方法详解,原型格局

By admin in 4858.com on 2019年4月11日

4858.com 14858.com 2

1.angular.bind()

4858.com 3

Python数据类型及其方法详解

我们在上学编程语言的时候,都会赶上数据类型,那种瞅着很基础也不明朗的东西,却是很首要,本文介绍了python的数据类型,并就每个数据类型的法子作出了详细的叙说,可供知识回想。

  1 /*2048*/
  2 
  3 #include<stdio.h>
  4 #include<stdlib.h>
  5 #include<conio.h>
  6 #include<time.h>
  7 
  8 void print(void);/*显示游戏界面*/
  9 int add(void);/*对中间变量数组进行处理*/
 10 
 11 int code[4][4] =
 12    {
 13     {0,0,0,0},
 14     {0,0,0,0},
 15     {0,0,0,0},
 16     {0,0,0,0},
 17    };/*游戏中的16个格子*/
 18 int temp[5];/*中间变量*/
 19 int move = 0;/*移动次数*/
 20 int score = 0;/*分数*/
 21 
 22 
 23 
 24 int main(void)
 25 {
 26      int gameover = 0;/*判断游戏是否结束,1结束,0继续*/
 27      int i,j;
 28      int change = 1;/*判断格子中的数是否改变,0不变*/
 29      char input;
 30      srand((unsigned)time(NULL));/*设置随机数的起点*/
 31      while(gameover == 0)
 32          {
 33               if(change >= 1)/*仅当数发生改变时添加新数*/
 34                {
 35                     do
 36                      {
 37                           i=((unsigned)rand()) % 4;
 38                           j=((unsigned)rand()) % 4;
 39                      }while(code[i][j] != 0);
 40                     if(((unsigned)rand()) % 4 == 0)
 41                      {
 42                           code[i][j]=4;
 43                      }
 44                     else
 45                      {
 46                           code[i][j]=2;/*随机选一个空格填上2或4*/
 47                      }
 48                     move++;/*增加次数*/
 49                }
 50               print();/*显示*/
 51               input = getch();/*输入方向*/
 52               change = 0;
 53               switch(input)
 54                    {
 55                         case '0':/*退出*/
 56                                  printf("Are you sure to exit?(y/n)");
 57                                  input=getchar();
 58                                  if(input=='y'||input=='Y')
 59                                     exit(0);
 60                                  break;
 61 
 62                         case 'W':
 63 
 64                         case 'w':/*上*/
 65                                  for(j=0;j<=3;j++)
 66                                    {
 67                                         for(i=0;i<=3;i++)
 68                                           {
 69                                                temp[i]=code[i][j];/*把一列数移到中间变量*/
 70                                           }
 71                                         temp[4]=0;
 72                                         change += add();
 73                                         for(i=0;i<=3;i++)
 74                                           {
 75                                                code[i][j]=temp[i];/*把处理好的中间变量移回来*/
 76                                           }
 77                                     }
 78                                   break;
 79 
 80                         case 'A':
 81 
 82                         case 'a':/*左*/
 83                                  for(i=0;i<=3;i++)
 84                                    {
 85                                         for(j=0;j<=3;j++)
 86                                           {
 87                                                temp[j]=code[i][j];/*把一行数移到中间变量*/
 88                                           }
 89                                         temp[4]=0;
 90                                         change += add();
 91                                         for(j=0;j<=3;j++)
 92                                           {
 93                                                code[i][j]=temp[j];/*把处理好的中间变量移回来*/
 94                                           }
 95                                    }
 96                                  break;
 97 
 98                         case 'S':
 99 
100                         case 's':/*下*/
101                                  for(j=0;j<=3;j++)
102                                    {
103                                         for(i=0;i<=3;i++)
104                                           {
105                                                temp[i]=code[3-i][j];/*把一列数移到中间变量*/
106                                           }
107                                         temp[4]=0;
108                                         change += add();
109                                         for(i=0;i<=3;i++)
110                                           {
111                                                code[3-i][j]=temp[i];/*把处理好的中间变量移回来*/
112                                           }
113                                    }
114                                  break;
115 
116                         case 'D':
117 
118                         case 'd':/*右*/
119                                  for(i=0;i<=3;i++)
120                                    {
121                                         for(j=0;j<=3;j++)
122                                           {
123                                                temp[j]=code[i][3-j];/*把一行数移到中间变量*/
124                                           }
125                                         temp[4]=0;
126                                         change += add();
127                                         for(j=0;j<=3;j++)
128                                           {
129                                                code[i][3-j]=temp[j];/*把处理好的中间变量移回来*/
130                                           }
131                                    }
132                                  break;
133                    }
134               gameover=1;
135               for(i=0;i<=3;i++)
136               for(j=0;j<=3;j++)
137               if(code[i][j]==0)
138               gameover=0;/*所有格子都填满则游戏结束*/
139         }
140     printf("Game over!\n");
141     getch();
142 
143     return 0;
144 }
145 
146 void print(void)/*显示游戏界面*/
147 {
148     int i,j;
149     system("CLS");/*清屏*/
150     printf("2048\n");
151     printf("W--UP A--LEFT S--DOWN D--RIGHT 0--EXIT\n");
152     printf("Score:%d Move:%d\n",score,move);
153     printf("Made by lanshanxiao\n");
154     printf("|-----------------------|\n");/*显示横向分隔线*/
155     for(i=0;i<=3;i++)
156        {
157            for(j=0;j<=3;j++)
158               {
159                    if(code[i][j]==0)
160                      {
161                           printf("|     ");/*0显示空格*/
162                      }
163                    else
164                      {
165                           printf("|%5d",code[i][j]);/*显示数字和分隔线*/
166                      }
167               }
168            printf("|\n|-----------------------|\n");/*显示横向分隔线*/
169        }
170 }
171 
172 int add(void)/*对中间变量数组进行处理*/
173 {
174     int i;
175     int t=0;
176     int change=0;/*判断数组是否有改变,0不变,1变化*/
177     do
178      {
179           for(i=0;i<=3;i++)
180             {
181                  if(temp[i]==0)
182                   {
183                        if(temp[i]!=temp[i+1])
184                          change=1;/*当一个0后面不是0时数组改变*/
185                        temp[i]=temp[i+1];
186                        temp[i+1]=0;
187                   }
188             }/*去掉中间的0*/
189           t++;
190      }while(t<=3);/*重复多次*/
191     for(i=1;i<=3;i++)
192         {
193              if(temp[i]==temp[i-1])
194               {
195                    if(temp[i]!=0)
196                      {
197                           change=1;/*当两个非零相同的数相加时数组改变*/
198                           score=score+temp[i];/*加分*/
199                      }
200                    temp[i-1]=temp[i-1]*2;
201                    temp[i]=0;
202               }
203         }/*把两个相邻的相同的数加起来*/
204 
205     return change;
206 }

4858.com 44858.com 5

原型情势正是从3个对象在创制其它贰个目的,不要求知道别的创制的细节:(克隆)

1、整型和长整型

整型:数据是不含有小数部分的数值型数据,比如大家所说的一、2、三、4、12二,其type为”int”

长整型:也是一种数字型数据,可是一般数字十分大,其type为”long”

在python第22中学差距整型和长整型,在3三位的机器上,取值范围是-214748364八~21474836四7,超出范围的为长整型,在60位的机器上,取值范围为-922337203685477580捌~922337203685477580柒(日常也与python的解释器的位数有关)。

在python三中,不设有整型和长整型之分,唯有整型。

举个例证:

4858.com 64858.com 7

python2中
number = 123
print (type(number))
number2 = 2147483647
print (type(number2))
number2 = 2147483648    #我们会看到超过2147483647这个范围,在py2中整形就会变成长整形了
print (type(number2))
#运行结果
<type 'int'>
<type 'int'>
<type 'long'>
#python3中
number = 123
print (type(number))
number2 = 2147483648   
print (type(number2))    #在python3中并不会
#运行结果
<class 'int'>
<class 'int'>

View Code

常用的method的如下:

.bit_length()

取最短bit位数

4858.com 84858.com 9

  def bit_length(self): # real signature unknown; restored from __doc__
        """
        int.bit_length() -> int

        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        6
        """
        return 0

View Code

举个例子:

4858.com 104858.com 11

number = 12  #1100 
print(number.bit_length())
#运行结果
4

View Code

 

View Code

<!DOCTYPE HTML>
<html ng-app>
<head>
</head>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</body>
<script>
  /*  angluar.bind(obj,fn,[args]) 把对象绑定到函数里,生成新的函数  */
    var obj={name:'xiaoming'};
    var fn= function (arg) {
        console.log(this.name+' is '+arg);  // this 指 obj
    }
    var f1=angular.bind(obj,fn,'so handsome'); // 参数可选
    f1();
    var f2=angular.bind(obj,fn);          // 可在最后才传参数
    f2('weak!');
</script>
</body>
</html>

以成立简历为例:

 二、浮点型

 浮点型能够看形成是小数,type为float。

4858.com 124858.com 13

#浮点型
number = 1.1
print(type(number))
#运行结果
<class 'float'>

View Code

 常用method的如下:

.as_integer_ratio()

回来元组(X,Y),number = k ,number.as_integer_ratio() ==>(x,y)
x/y=k

4858.com 144858.com 15

    def as_integer_ratio(self): # real signature unknown; restored from __doc__
        """
        float.as_integer_ratio() -> (int, int)

        Return a pair of integers, whose ratio is exactly equal to the original
        float and with a positive denominator.
        Raise OverflowError on infinities and a ValueError on NaNs.

        >>> (10.0).as_integer_ratio()
        (10, 1)
        >>> (0.0).as_integer_ratio()
        (0, 1)
        >>> (-.25).as_integer_ratio()
        (-1, 4)
        """
        pass

View Code

 举个例证

4858.com 164858.com 17

number = 0.25
print(number.as_integer_ratio())
#运行结果
(1, 4)

View Code

.hex()

 以十6进制表示浮点数

4858.com 184858.com 19

    def hex(self): # real signature unknown; restored from __doc__
        """
        float.hex() -> string

        Return a hexadecimal representation of a floating-point number.
        >>> (-0.1).hex()
        '-0x1.999999999999ap-4'
        >>> 3.14159.hex()
        '0x1.921f9f01b866ep+1'
        """
        return ""

View Code

 举个例子

4858.com 204858.com 21

number = 3.1415
print(number.hex())
#运行结果
0x1.921cac083126fp+1

View Code

.fromhex()

将十陆进制小数以字符串输入,重返10进制小数

4858.com 224858.com 23

    def fromhex(string): # real signature unknown; restored from __doc__
        """
        float.fromhex(string) -> float

        Create a floating-point number from a hexadecimal string.
        >>> float.fromhex('0x1.ffffp10')
        2047.984375
        >>> float.fromhex('-0x1p-1074')
        -5e-324
        """

View Code

举个例证

4858.com 244858.com 25

print(float.fromhex('0x1.921cac083126fp+1'))
#运行结果
3.1415

View Code

.is_integer()

认清小数是否整数,比如3.0为三个整数,而三.壹不是,再次来到布尔值

4858.com 264858.com 27

    def is_integer(self, *args, **kwargs): # real signature unknown
        """ Return True if the float is an integer. """
        pass

View Code

举个例子

4858.com 284858.com 29

number = 3.1415
number2 = 3.0
print(number.is_integer())
print(number2.is_integer())
#运行结果
False
True

View Code

 

204八小游戏代码在上边的View Code中,将加号展开就足以见到。

View Code

简历类(Resume) :继承于系统的克隆接口(ICloneable)

三、字符类型

字符串正是局地列的字符,在Python中用单引号或然双引号括起来,多行能够用3引号。

4858.com 304858.com 31

name = 'my name is Frank'
name1 = "my name is Frank"
name2 = '''my name is Frank
I'm 23 years old,      
       '''
print(name)
print(name1)
print(name2)
#运行结果
my name is Frank
my name is Frank
my name is Frank
I'm 23 years old  

View Code

常用method的如下:

.capitalize()

字符串首字符大写

4858.com 324858.com 33

  def capitalize(self): # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str

        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""

View Code

举个例证

4858.com 344858.com 35

name = 'my name is Frank'
#运行结果
My name is frank

View Code

.center()

字符居中,内定宽度和填充字符(暗许为空格)

4858.com 364858.com 37

  def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str

        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

View Code

举个例证

4858.com 384858.com 39

flag = "Welcome Frank"
print(flag.center(50,'*'))
#运行结果
******************Welcome Frank*******************

View Code

.count()

计量字符串中有个别字符的个数,可以钦命索引范围

4858.com 404858.com 41

    def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int

        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0

View Code

举个例证

4858.com 424858.com 43

flag = 'aaababbcccaddadaddd'
print(flag.count('a'))
print(flag.count('a',0,3))
#运行结果
7
3

View Code

.encode()

编码,在python三中,str暗中同意是unicode数据类型,能够将其编码成bytes数据

4858.com 444858.com 45

    def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes

        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""

View Code

举个例证

4858.com 464858.com 47

flag = 'aaababbcccaddadaddd'
print(flag.encode('utf8'))
#运行结果
b'aaababbcccaddadaddd'

View Code

.endswith()

看清字符串结尾是不是是某些字符串和字符,能够通过索引钦定范围

4858.com 484858.com 49

   def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool

        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

View Code

举个例子

4858.com 504858.com 51

flag = 'aaababbcccaddadaddd'
print(flag.endswith('aa'))
print(flag.endswith('ddd'))
print(flag.endswith('dddd'))
print(flag.endswith('aaa',0,3))
print(flag.endswith('aaa',0,2))
#运行结果
False
True
False
True
False

View Code

.expandtabs()

把制表符tab(“\t”)转换为空格

4858.com 524858.com 53

  def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str

        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

View Code

举个例证

4858.com 544858.com 55

flag = "\thello python!"
print(flag)
print(flag.expandtabs())   #默认tabsize=8
print(flag.expandtabs(20))
#运行结果
    hello python!             #一个tab,长度为4个空格
        hello python!         #8个空格
                    hello python!    #20个空格

View Code

.find()

摸索字符,重临索引值,能够透过点名索引范围内搜索,查找不到重回-1

4858.com 564858.com 57

    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int

        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

View Code

举个例子

4858.com 584858.com 59

flag = "hello python!"
print(flag.find('e'))
print(flag.find('a'))
print(flag.find('h',4,-1))
#运行结果
1
-1
9

View Code

.format()

格式化输出,使用”{}”符号作为操作符。

4858.com 604858.com 61

def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str

        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

View Code

举个例子

4858.com 624858.com 63

#位置参数
flag = "hello {0} and {1}!"
print(flag.format('python','php'))
flag = "hello {} and {}!"
print(flag.format('python','php'))
#变量参数
flag = "{name} is {age} years old!"
print(flag.format(name='Frank',age = 23))
#结合列表
infor=["Frank",23]
print("{0[0]} is {0[1]} years old".format(infor))
#运行结果
hello python and php!
hello python and php!
Frank is 23 years old!
Frank is 23 years old

View Code

.format_map()

格式化输出

4858.com 644858.com 65

 def format_map(self, mapping): # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str

        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""

View Code

举个例证

4858.com 664858.com 67

people={
    'name':['Frank','Caroline'],
    'age':['23','22'],
}
print("My name is {name[0]},i am {age[1]} years old !".format_map(people))
#运行结果
My name is Frank,i am 22 years old !

View Code

.index()

听说字符查找索引值,能够钦点索引范围查找,查找不列席报错

4858.com 684858.com 69

 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int

        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

View Code

举个例子

4858.com 704858.com 71

flag = "hello python!"
print(flag.index("e"))
print(flag.index("o",6,-1))
#运行结果
1
10

View Code

.isalnum()

判断是不是是字母或数字构成,重返布尔值

4858.com 724858.com 73

def isalnum(self): # real signature unknown; restored from __doc__
        """
        S.isalnum() -> bool

        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例证

4858.com 744858.com 75

flag = "hellopython"
flag1 = "hellopython22"
flag2 = "hellopython!!"
flag3 = "!@#!#@!!@"
print(flag.isalnum())
print(flag1.isalnum())
print(flag2.isalnum())
print(flag3.isalnum())
#运行结果
True
True
False
False

【4858.com】Python数据类型及其方法详解,原型格局。View Code

.isalpha()

判断是还是不是是字母组合,重返布尔值

4858.com 764858.com 77

 def isalpha(self): # real signature unknown; restored from __doc__
        """
        S.isalpha() -> bool

        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例子

4858.com 784858.com 79

flag = "hellopython"
flag1 = "hellopython22"
print(flag.isalpha())
print(flag1.isalpha())
#运行结果
True
False

View Code

.isdecimal()

判断是或不是是二个⑩进制正整数,重返布尔值

4858.com 804858.com 81

  def isdecimal(self): # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool

        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False

View Code

举个例证

4858.com 824858.com 83

number = "1.2"
number1 = "12"
number2 = "-12"
number3 = "1222"
print(number.isdecimal())
print(number1.isdecimal())
print(number2.isdecimal())
print(number3.isdecimal())
#运行结果
False
True
False
True

View Code

isdigit()

判断是不是是一个正整数,重临布尔值,与地点isdecimal类似

4858.com 844858.com 85

  def isdigit(self): # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool

        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例证

4858.com 864858.com 87

number = "1.2"
number1 = "12"
number2 = "-12"
number3 = "11"
print(number.isdigit())
print(number1.isdigit())
print(number2.isdigit())
print(number3.isdigit())
#运行结果
False
True
False
True

View Code

.isidentifier()

判断是或不是为python中的标识符

4858.com 884858.com 89

 def isidentifier(self): # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool

        Return True if S is a valid identifier according
        to the language definition.

        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False

View Code

举个例证

4858.com 904858.com 91

flag = "cisco"
flag1 = "1cisco"
flag2 = "print"
print(flag.isidentifier())
print(flag1.isidentifier())
print(flag2.isidentifier())
#运行结果
True
False
True

View Code

.islower()

 判断字符串中的字母是或不是都是小写,重临布尔值

4858.com 924858.com 93

    def islower(self): # real signature unknown; restored from __doc__
        """
        S.islower() -> bool

        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

View Code

举个例子

4858.com 944858.com 95

flag = "cisco"
flag1 = "cisco222"
flag2 = "Cisco"
print(flag.islower())
print(flag1.islower())
print(flag2.islower())
#运行结果
True
True
False

View Code

.isnumeric()

认清是还是不是为数字,那几个很强大,普通话字符,繁体字数字都得以辨别

4858.com 964858.com 97

 def isnumeric(self): # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool

        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False

View Code

举个例子

4858.com 984858.com 99

number = "123"
number1 = "一"
number2 = "壹"
number3 = "123q"
number4 = "1.1"
print(number.isnumeric())
print(number1.isnumeric())
print(number2.isnumeric())
print(number3.isnumeric())
print(number4.isnumeric())
#运行结果
True
True
True
False
False

View Code

.isprintable()

判断引号里面包车型地铁是否都以可打字与印刷的,再次回到布尔值

4858.com 1004858.com 101

   def isprintable(self): # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool

        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False

View Code

举个例子

4858.com 1024858.com 103

flag = "\n123"
flag1 = "\t"
flag2 = "123"
flag3 = r"\n123"    # r 可以是转义字符失效
print(flag.isprintable())     #\n不可打印
print(flag1.isprintable())    #\t不可打印
print(flag2.isprintable())
print(flag3.isprintable())
#运行结果
False
False
True
True

View Code

.isspace()

判断字符串里面都以一无所得位,空格大概tab,重返布尔值

4858.com 1044858.com 105

  def isspace(self): # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool

        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例证

4858.com 1064858.com 107

flag = '    '     #4个空格
flag1 = '        '#2个tab
print(flag.isspace())
print(flag1.isspace())
#运行结果
True
True

View Code

.istitle()

判定字符串里面包车型地铁字符是还是不是都以大写发轫,重回布尔值

4858.com 1084858.com 109

  def isspace(self): # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool

        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例证

4858.com 1104858.com 111

flag = "Welcome Frank"
flag1 = "Welcome frank"
print(flag.istitle())
print(flag1.istitle())
#运行结果
True
False

View Code

.isupper()

看清是不是都以字符串里的字母都以大写

4858.com 1124858.com 113

    def isupper(self): # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool

        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

View Code

举个例子

4858.com 1144858.com 115

flag = "WELCOME1"
flag1 = "Welcome1"
print(flag.isupper())
print(flag1.isupper())
#运行结果
True
False

View Code

.join()

将字符串以内定的字符连接生成三个新的字符串

4858.com 1164858.com 117

  def join(self, iterable): # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str

        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

View Code

举个例子

4858.com 1184858.com 119

flag = "welcome"
print("#".join(flag))
#运行结果
w#e#l#c#o#m#e

View Code

.ljust()

左对齐,可钦赐字符宽度和填充字符

4858.com 1204858.com 121

   def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str

        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

View Code

举个例证

4858.com 1224858.com 123

flag = "welcome"
print(flag.ljust(20,"*"))
#运行结果
welcome*************

View Code

.rjust()

右对齐,可钦赐字符宽度和填充字符

4858.com 1244858.com 125

    def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str

        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

View Code

举个例子

4858.com 1264858.com 127

flag = "welcome"
print(flag.rjust(20,"*"))
#运行结果
*************welcome

View Code

.lower()

对字符串里的装有字母转小写

4858.com 1284858.com 129

    def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str

        Return a copy of the string S converted to lowercase.
        """
        return ""

View Code

举个例证

4858.com 1304858.com 131

flag = "WELcome"
#运行结果
welcome

View Code

.upper()

对字符串里的保有字母转大写

4858.com 1324858.com 133

    def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str

        Return a copy of S converted to uppercase.
        """
        return ""

View Code

举个例证

4858.com 1344858.com 135

flag = "WELcome"
print(flag.upper())
#运行结果
WELCOME

View Code

.title()

对字符串里的单词进行首字母大写转换

4858.com 1364858.com 137

    def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str

        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""

View Code

举个例证

4858.com 1384858.com 139

flag = "welcome frank"
print(flag.title())
#运行结果
Welcome Frank

View Code

.lstrip()

暗许去除右边空白字符,可钦定去除的字符,去除钦点的字符后,会被空白占位。

4858.com 1404858.com 141

  def lstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str

        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

View Code

举个例证

4858.com 1424858.com 143

flag = "     welcome frank"
flag1 = "@@@@welcome frank"
print(flag.lstrip())
print(flag.lstrip("@"))
print(flag.lstrip("@").lstrip())
#运行结果
welcome frank
     welcome frank
welcome frank

View Code

.rstrip()

默许去除左边空白字符,可钦点去除的字符,去除钦定的字符后,会被空白占位。

4858.com 1444858.com 145

 def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str

        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

View Code

举个例证

4858.com 1464858.com 147

flag = "welcome frank    "
flag1 = "welcome frank@@@@"
# print(flag.title())
print(flag.rstrip())
print(flag.rstrip("@"))
print(flag.rstrip("@").rstrip())
#运行结果
welcome frank
welcome frank    #右边有4个空格
welcome frank

View Code

.strip()

私下认可去除两边空白字符,可钦赐去除的字符,去除内定的字符后,会被空白占位。

4858.com 1484858.com 149

    def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str

        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

View Code

举个例证

4858.com 1504858.com 151

flag = "    welcome frank    "
flag1 = "@@@@welcome frank@@@@"
# print(flag.title())
print(flag.strip())
print(flag.strip("@"))
print(flag.strip("@").strip())
#运行结果
welcome frank
    welcome frank    #右边有4个空格
welcome frank

View Code

.maketrans()和translate()

创办字符映射的转换表,对于收受三个参数的最简便易行的调用格局,第三个参数是字符串,表示须求转移的字符,第二个参数也是字符串表示转换的对象。七个字符串的长度必须一致,为顺序对应的关系。

4858.com 1524858.com 153

   def maketrans(self, *args, **kwargs): # real signature unknown
        """
        Return a translation table usable for str.translate().

        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass

View Code

4858.com 1544858.com 155

  def translate(self, table): # real signature unknown; restored from __doc__
        """
        S.translate(table) -> str

        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""

View Code

举个例证

4858.com 1564858.com 157

intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print (str.translate(trantab))
#运行结果
th3s 3s str3ng 2x1mpl2....w4w!!!

View Code

.partition()

以钦定字符分割,再次来到三个元组

4858.com 1584858.com 159

 def partition(self, sep): # real signature unknown; restored from __doc__
        """
        S.partition(sep) -> (head, sep, tail)

        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass

View Code

举个例证

4858.com 1604858.com 161

flag = "welcome"
print(flag.partition("e"))
#运行结果
('w', 'e', 'lcome')

View Code

.replace()

将内定的字符替换为新的字符,可钦定替换的个数

4858.com 1624858.com 163

    def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str

        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

View Code

举个例子

4858.com 1644858.com 165

flag = "welcome frank ,e.."
print(flag.replace("e","z"))
print(flag.replace("e","z",1))
#运行结果
wzlcomz frank ,z..
wzlcome frank ,e..

View Code

.rfind()

归来字符串第贰遍面世的地方,从右向左差,重临索引值,若未有,则赶回-壹,可依照目录范围查找

4858.com 1664858.com 167

   def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int

        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

View Code

举个例证

4858.com 1684858.com 169

flag = "welcome frank ,e.."
print(flag.rfind("e"))
print(flag.rfind("x"))
print(flag.rfind("e",0,3))
#运行结果
15
-1
1

View Code

.rindex()

 查找字符索引值,从右向左,重回索引值,与rfind类似,查找不参与报错

4858.com 1704858.com 171

 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int

        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

View Code

举个例证

4858.com 1724858.com 173

flag = "welcome frank ,e.."
print(flag.rindex("e"))
print(flag.rindex("e",0,3))
#运行结果
15
1

View Code

.rpartition()

以钦定字符从右向左分割,只分割二次,重返元组,若未有点名的字符,则在重临的元组前面加四个空字符串

4858.com 1744858.com 175

    def rpartition(self, sep): # real signature unknown; restored from __doc__
        """
        S.rpartition(sep) -> (head, sep, tail)

        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass

View Code

举个例证

4858.com 1764858.com 177

flag = "welcome frank ,e.."
print(flag.rpartition("e"))
print(flag.rpartition("x"))
#运行结果
('welcome frank ,', 'e', '..')
('', '', 'welcome frank ,e..')

View Code

.split()

分割,能够以钦命的字符分割,可内定分割的次数,私下认可从左向右分割,与partition分裂的是,split分割后会删除钦赐的字符,暗中认可以空格为分割符,重回元组。

4858.com 1784858.com 179

    def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []

View Code

举个例子

4858.com 1804858.com 181

flag = "welcome frank, e.."
print(flag.split())
print(flag.split('e'))
print(flag.split('e',1))
#运行结果
['welcome', 'frank,', 'e..']
['w', 'lcom', ' frank, ', '..']
['w', 'lcome frank, e..']

View Code

.rsplit()

与split类似,只是它是从右向左分

4858.com 1824858.com 183

    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []

View Code

举个例子

4858.com 1844858.com 185

flag = "welcome frank, e.."
print(flag.rsplit())
print(flag.rsplit('e'))
print(flag.rsplit('e',1))
#运行结果
['welcome', 'frank,', 'e..']
['w', 'lcom', ' frank, ', '..']
['welcome frank, ', '..']

View Code

.splitlines()

字符串转换为列表

4858.com 1864858.com 187

    def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings

        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

View Code

举个例证

4858.com 1884858.com 189

info = "hello,my name is Frank"
print(info.splitlines())
#运行结果
['hello,my name is Frank']

View Code

.startswith()

判定是不是以钦定字符串或字符早先,可内定索引范围,重回布尔值

4858.com 1904858.com 191

 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool

        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

View Code

举个例子

4858.com 1924858.com 193

info = "hello,my name is Frank"
print(info.startswith("he"))
print(info.startswith("e"))
print(info.startswith("m",6,-1))
#运行结果
True
False
True

View Code

.swapcase()

将字符串中的大小写沟通

4858.com 1944858.com 195

   def swapcase(self): # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str

        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""

View Code

4858.com,举个例子

4858.com 1964858.com 197

info = "Hello,My name is Frank"
print(info.swapcase())
#运行结果
hELLO,mY NAME IS fRANK

View Code

.zfill()

点名字符串宽度,不足的入手填“0”

4858.com 1984858.com 199

    def zfill(self, width): # real signature unknown; restored from __doc__
        """
        S.zfill(width) -> str

        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""

View Code

举个例子

4858.com 2004858.com 201

info = "Hello,My name is Frank"
print(info.zfill(50))
#运行结果
0000000000000000000000000000Hello,My name is Frank

View Code

 

点击源码上的复制按键还足以一贯将源代码复制下来。

 2.angular.bootstrap()

4858.com 2024858.com 203

四、列表

列表是由1密密麻麻按一定顺序排列的要素构成。在python中,用方括号([]),来代表列表,并用逗号来划分在那之中的因素,我们来看一下总结的列表,其type为”list”

4858.com 2044858.com 205

name = ['Frank','Caroline','Bob','Saber']
print(name)  #直接打印会将中括号、引号和逗号都打印出来
print(name[1]) #添加索引可打印对应的值,从索引值从0开始
print(name[-1]) #打印最后一个元素
print(name[0:2]) #用冒号来切片,取右不取左
print(name[-2:]) #冒号右边不写代表一直打印到最后一个
print(name[:1]) #冒号左边不写代表从第“0”个开始打印

View Code

 常见方法如下:

.index()

 查找对应成分的索引值,再次回到索引值,能够钦命索引范围来查找,查找不到位报错

4858.com 2064858.com 207

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

View Code

 举个例子

4858.com 2084858.com 209

name = ['Frank','Caroline','Bob','Saber']
print(name.index("Frank"))
print(name.index("Bob",1,-1))
#运行结果
0
2

View Code

.count()

 总计某些成分的个数

4858.com 2104858.com 211

  def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

View Code

 举个例证

4858.com 2124858.com 213

name = ['Frank','Caroline','Bob','Saber','Frank']
print(name.count('Frank'))
#运行结果
2

View Code

 .append()

 在列表的末段添日成分

4858.com 2144858.com 215

    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        pass

View Code

 举个例证

4858.com 2164858.com 217

name = ['Frank','Caroline','Bob','Saber','Frank']
name.append('Mei')
print(name)
#运行结果
['Frank', 'Caroline', 'Bob', 'Saber', 'Frank', 'Mei']

View Code

.clear()

 清空驶列车表

4858.com 2184858.com 219

 def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        pass

View Code

 举个例证

4858.com 2204858.com 221

name = ['Frank','Caroline','Bob','Saber','Frank']
name.clear()
print(name)
#运行结果
[]

View Code

 .copy()

 复制列表

4858.com 2224858.com 223

   def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        return []

View Code

 举个例子

4858.com 2244858.com 225

name = ['Saber','Frank',1,2,[3,4]]
name_cp = name.copy()
print(name_cp)
name[0]='Tom'
name[3]='7'
name[4][0]='8'
print(name)
print(name_cp)
#运行结果
['Saber', 'Frank', 1, 2, [3, 4]]
['Tom', 'Frank', 1, '7', ['8', 4]]
['Saber', 'Frank', 1, 2, ['8', 4]]

View Code

我们会发觉,我们给name[0]、name[3]、和name[4][0]都重新赋值了,为啥本身再一次赋值的name[4][0]会潜移默化到作者复制的列表的吧?

先是我们来看一下这么些复制图解:

 4858.com 226

咱俩在复制的时候,新复制的列表都会针对被复制列表的地方空间,name[4]和name_cp[4]本人也是个列表,它们对准的是同贰个列表地址空间。大家来看一下给name列表重新赋值后,地址空间的扭转:

 4858.com 227

 重新赋值后,内部存储器给name[3]、name[0]、name[4][0]都再也开发了壹块内存空间,name[0]本着了内部存款和储蓄器地址3870343贰,name[3]本着了内部存款和储蓄器地址1400943960,而name[4]要么指向3709293陆,可是内部存款和储蓄器地址3709293陆指向name[4][0]内部存款和储蓄器地址发生了变通,指向了1400944350,所以,在列表中的列表大家给它再也赋值的时候,也会改变复制列表的值,因为它们的列表里的列表都以指向同1块地点空间。那么1旦大家想完全复制怎么办吧?

 能够调用函数deepcopy().

4858.com 2284858.com 229

import copy
name = ['Saber','Frank',1,2,[3,4]]
name_cp=copy.deepcopy(name)
name[4][0]=5
print(name)
print(name_cp)
#运行结果
['Saber', 'Frank', 1, 2, [5, 4]]
['Saber', 'Frank', 1, 2, [3, 4]]

View Code

 4858.com 230

 这样会给复制后的列表中的列表重新开发一个地方空间,然后指向列表中列表的要素的地址空间,那样您怎么转移原列表name,name_copy都不会转移。

.extend()

 函数用于在列表末尾三次性追加另一个行列中的多个值(用新列表扩张原来的列表)。

4858.com 2314858.com 232

 def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        pass

View Code

 举个例子

4858.com 2334858.com 234

name = ['Saber','Frank']
nameto = ['Mei','Jack']
name.extend(nameto)
print(name)
#运行结果
['Saber', 'Frank', 'Mei', 'Jack']

View Code

insert()

安顿成分,必要内定索引值来插入

4858.com 2354858.com 236

 def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

View Code

 举个例证

4858.com 2374858.com 238

name = ['Saber','Frank']
name.insert(0,'Jack')
print(name)
#运行结果
['Jack', 'Saber', 'Frank']

View Code

 .pop()

 弹出成分,暗中认可弹出最终三个要素,能够钦赐索引,弹出相应的成分,当列表弹空可能尚未点名的索引值会报错,并重返弹出的值

4858.com 2394858.com 240

 def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

View Code

举个例子

4858.com 2414858.com 242

name = ['Saber','Frank','Caroline','Jack']
name.pop()
print(name)
name = ['Saber','Frank','Caroline','Jack']
name.pop(1)
print(name)
#运行结果
['Saber', 'Frank', 'Caroline']
['Saber', 'Caroline', 'Jack']

View Code

.remove()

移除钦命的要素

4858.com 2434858.com 244

def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

View Code

 举个例证

4858.com 2454858.com 246

name = ['Saber','Frank','Caroline','Jack']
name.remove('Frank')
print(name)
#运行结果
['Saber', 'Caroline', 'Jack']

View Code

.reverse()

 列表反转,永久修改

4858.com 2474858.com 248

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

View Code

 举个例证

4858.com 2494858.com 250

name = ['Saber','Frank','Caroline','Jack']
name.reverse()
print(name)
#运行结果
['Jack', 'Caroline', 'Frank', 'Saber']

View Code

.sort()

对列表实行排序,永久修改,如果列表中同时存在不一样类型的数额,则不能够排序,比如含有整型和字符串,传递reverse=True能够倒着排序。

4858.com 2514858.com 252

 def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass

View Code

举个例证

4858.com 2534858.com 254

name = ['Saber','Frank','Caroline','Jack','1','abc','xyz']
name.sort()
print(name)
name.sort(reverse=True)
print(name)
#运行结果
['1', 'Caroline', 'Frank', 'Jack', 'Saber', 'abc', 'xyz']
['xyz', 'abc', 'Saber', 'Jack', 'Frank', 'Caroline', '1']
number = [1,2,3,42,12,32,43,543]
number.sort()
print(number)
number.sort(reverse=True)
print(number)
#运行结果
[1, 2, 3, 12, 32, 42, 43, 543]
[543, 43, 42, 32, 12, 3, 2, 1]

View Code

 

 

4858.com 2554858.com 256

namespace Ptototype_Pattern
{
    class ReSume:ICloneable
    {
        private string name;
        private string age;
        private string sex;
        private string birthday;
        private string time;
        private string company;
        public ReSume(string name)
        {
            this.name = name;
        }

        /// <summary>
        /// 设置个人信息
        /// </summary>
        /// <param name="age"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        public void SetPersonInfo(string age, string sex, string birthday)
        {
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
        }

        /// <summary>
        /// 设置工作经历
        /// </summary>
        /// <param name="time"></param>
        /// <param name="company"></param>
        public void SetWorkExperice(string time, string company)
        {
            this.time = time;
            this.company = company;
        }

        public void Display()
        {
            Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            Console.WriteLine("在 {0} 工作于 {1} \n",time,company);
        }

        public Object Clone()
        {
            return (Object)this.MemberwiseClone();
        }
    }
}

五、元组

元组和列表类似,不一致的是元组的要素是不可能修改的,使用小括号”()”括起来,用逗号”,”分开,其type为tuple

4858.com 2574858.com 258

number = (1,2,2,2,1)
print(type(number))
print(number[0])
print(number[-1])
print(number[1:])
#运行结果
<class 'tuple'>
1
1
(2, 2, 2, 1)

View Code

大面积方式如下:

.count()

总计钦定成分的个数

4858.com 2594858.com 260

   def count(self, value): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0

View Code

举个例子

4858.com 2614858.com 262

number = (1,2,2,2,1)
print(number.count(2))
#运行结果
3

View Code

.index()

查找内定成分的目录,能够钦定索引范围来搜寻

4858.com 2634858.com 264

 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

View Code

举个例证

4858.com 2654858.com 266

number = (1,2,2,2,1)
print(number.index(2))
print(number.index(2,2,-1))
#运行结果
1
2

View Code

 

 

<!DOCTYPE HTML>
<meta charset="utf-8">
<head>
</head>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</body>
<script>
    //   angular.bootstrap(); 手动加载模块,   模仿 ng-app自动加载模块    注意不能出现  ng-app
    //创建模块1
  var module1=angular.module('module1',[]);
    module1.controller('controller1', function ($scope) {
        $scope.name='haha';
    })
    //创建模块2
  var module2=angular.module('module2',[]);
  module2.controller('controller2', function ($scope) {
      $scope.name='hehe';
  })
    // 页面加载完成后再加载模块
    angular.element(document).ready(function () {
        angular.bootstrap(document.getElementById("div1"),["module1"]);    //  div1加载 模块1
        angular.bootstrap(document.getElementById("div2"),["module2"]);
    })
</script>
<div id="div1" ng-controller="controller1">div1: {{name}}</div>   <!--  这里要有控制器 -->
<div id="div2" ng-controller="controller2">div2: {{name}}</div>
</body>
</meta>

View Code

六、集合

会见是一名目繁多无序的成分结合,全部你不可能使用索引值,在打印的时候,元组是当然排序,天然去重的,其type为set

4858.com 2674858.com 268

number = {1,2,3,4,4,5,6}
number1 = {1,6,2,1,8,9,10}
print(number)
print(number1)
#运行结果
{1, 2, 3, 4, 5, 6}
{1, 2, 6, 8, 9, 10}

View Code

常用方法如下

.remove()

移除钦定的因素

4858.com 2694858.com 270

  def remove(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set; it must be a member.

        If the element is not a member, raise a KeyError.
        """
        pass

View Code

举个例子

4858.com 2714858.com 272

number = {1,2,3,4,4,5,6}
print(number)
number.remove(1)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6}
{2, 3, 4, 5, 6}

View Code

.pop()

弹出排序过后的首先个因素

4858.com 2734858.com 274

    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass

View Code

 

举个例子

4858.com 2754858.com 276

number = {1,2,3,4,4,5,6}
print(number)
number_pop = number.pop()
print(number_pop)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6}
1
{2, 3, 4, 5, 6}

View Code

.clear()

清空驶列车表重返set()

4858.com 2774858.com 278

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass

View Code

举个例证

4858.com 2794858.com 280

number = {1,2,3,4,4,5,6}
print(number)
number.clear()
print(number)
#运行结果
{1, 2, 3, 4, 5, 6}
set()

View Code

.copy()

复制集合

4858.com 2814858.com 282

   def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        pass

View Code

举个例证

4858.com 2834858.com 284

number = {1,2,3,4,4,5,6}
print(number)
number2 = number.copy()
number.pop()
print(number)
print(number2)
#运行结果
{1, 2, 3, 4, 5, 6}
{2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}

View Code

.add()

添美金素

4858.com 2854858.com 286

    def add(self, *args, **kwargs): # real signature unknown
        """
        Add an element to a set.

        This has no effect if the element is already present.
        """
        pass

View Code

举个例子

4858.com 2874858.com 288

number = {1,2,3,4,4,5,6}
print(number)
number.add(7)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6, 7}

View Code

.difference()

求差集,可以用“-”代替

4858.com 2894858.com 290

    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set.

        (i.e. all elements that are in this set but not the others.)
        """
        pass

View Code

举个例证

4858.com 2914858.com 292

number = {1,2,3,4,5,6,8,9}
number1 = {2,3,8,9,11,12,10}
print(number.difference(number1))
print(number1.difference(number))
print(number - number1)
print(number1 - number)
##运行结果
{1, 4, 5, 6}
{10, 11, 12}
{1, 4, 5, 6}
{10, 11, 12}

View Code

.union()

求并集,可用“|”代替

4858.com 2934858.com 294

    def union(self, *args, **kwargs): # real signature unknown
        """
        Return the union of sets as a new set.

        (i.e. all elements that are in either set.)
        """
        pass

View Code

举个例证

4858.com 2954858.com 296

number = {1,2,3,4,5,6,8,9}
number1 = {2,3,8,9,11,12,10}
print(number.union(number1))
print(number | number1)
#运行结果
{1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12}
{1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12}

View Code

difference_update.()

差异更新,未有再次来到值,直接改动集合

4858.com 2974858.com 298

    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set. """
        pass

View Code

举个例证

4858.com 2994858.com 300

number = {1,2,3,4,5,6,8,9,13}
number1 = {2,3,8,9,11,12,10}
number.difference_update(number1)
print(number)
#运行结果
{1, 4, 5, 6, 13}

View Code

.discard()

 移除钦点成分,假使集合内未有点名的成分,就什么样都不做

4858.com 3014858.com 302

    def discard(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set if it is a member.

        If the element is not a member, do nothing.
        """
        pass

View Code

举个例子

4858.com 3034858.com 304

number = {1,2,3,4,5,6,8,9,13}
number.discard(1)
print(number)
#运行结果
{2, 3, 4, 5, 6, 8, 9, 13}

View Code

.intersection()

交集,可以用”&”代替

4858.com 3054858.com 306

def intersection(self, *args, **kwargs): # real signature unknown
        """
        Return the intersection of two sets as a new set.

        (i.e. all elements that are in both sets.)
        """
        pass

View Code

举个例子

4858.com 3074858.com 308

number = {1,2,3,4,5,6,8,9,13}
number1 = {1,2,3,4,5,13,16,17}
print(number.intersection(number1))
print(number & number1)
#运行结果
{1, 2, 3, 4, 5, 13}
{1, 2, 3, 4, 5, 13}

View Code

.intersection_update()

混合更新,未有重临值,直接修改集合

4858.com 3094858.com 310

 def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another. """
        pass

View Code

举个例证

4858.com 3114858.com 312

number = {1,2,3,4,5,6,8,9,13}
number1 = {1,2,3,4,5,13,16,17}
number.intersection_update(number1)
print(number)
#运行结果
{1, 2, 3, 4, 5, 13}

View Code

isdisjoint()

当五个集聚未有交集的时候,重回True,不然再次回到False

4858.com 3134858.com 314

  def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection. """
        pass

View Code

举个例证

4858.com 3154858.com 316

number = {1,2,3,4,5,6,8,9,13}
number1 = {16,17}
print(number.isdisjoint(number1))
#运行结果
True
number = {1,2,3,4,5,6,8,9,13,16}
number1 = {16,17}
#运行结果
False

View Code

.issubset()

 当有三个集合A和B,A.issubset(B),A是还是不是被B包蕴,要是是则赶回True,不然重临False

4858.com 3174858.com 318

  def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set. """
        pass

View Code

举个例证

4858.com 3194858.com 320

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17}
print(number1.issubset(number))
#运行结果
True

View Code

.issuperset()

当有1个集合A和B,A.issuperset(B),A是不是包蕴B,如果带有则赶回True,不然重临False

4858.com 3214858.com 322

 def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. """
        pass

View Code

举个例证

4858.com 3234858.com 324

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17}
print(number.issuperset(number1))
#运行结果
True

View Code

.symmetric_difference()

取三个汇集的差集,即取三个集聚中对方都未有的要素

4858.com 3254858.com 326

  def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """
        Return the symmetric difference of two sets as a new set.

        (i.e. all elements that are in exactly one of the sets.)
        """
        pass

View Code

举个例证

4858.com 3274858.com 328

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17,18,19}
print(number.symmetric_difference(number1))
#运行结果
{1, 2, 3, 4, 5, 6, 8, 9, 13, 18, 19}

View Code

.symmetric_difference_update()

取八个聚众的差集,即取七个汇集中对方都不曾的因素,并立异到集结中

4858.com 3294858.com 330

   def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. """
        pass

View Code

举个例子

4858.com 3314858.com 332

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17,18,19}
number.symmetric_difference_update(number1)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6, 8, 9, 13, 18, 19}

View Code

.update()

取七个汇聚的并集,并更新到集结中

4858.com 3334858.com 334

  def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. """
        pass

View Code

举个例证

4858.com 3354858.com 336

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17,18,19}
number.update(number1)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6, 8, 9, 13, 16, 17, 18, 19}

View Code

 

 

View Code

客户端类(TestMain)

七、字典

在python里面,字典正是1多级的 键-值,每种值都与1个值是逐壹对应的,键能够是数字、字符串、列表和字典。实际上,能够将别的python对象用作字典的值。

4858.com 3374858.com 338

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
print(info)
print(info['age'])
#运行结果
{'name': 'Frank', 'age': 23, 'hobbby': 'reading', 'address': 'Shanghai'}
23

View Code

形式如下:

.keys()

取出字典的键

4858.com 3394858.com 340

   def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

View Code

举个例证

4858.com 3414858.com 342

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
print(info.keys())
#运行结果
dict_keys(['name', 'age', 'hobbby', 'address'])

View Code

.values()

取出字典的值

4858.com 3434858.com 344

  def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass

View Code

举个例子

4858.com 3454858.com 346

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
#运行结果
print(info.values())

View Code

.pop()

 弹出二个键值对,必须内定键

 举个例子

4858.com 3474858.com 348

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
info.pop('name')
print(info)
#运行结果
{'age': 23, 'hobbby': 'reading', 'address': 'Shanghai'}

View Code

 .clear()

 清空字典里的键值对

4858.com 3494858.com 350

 def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass

View Code

 举个例证

4858.com 3514858.com 352

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
info.clear()
print(info)
#运行结果
{}

View Code

 .update()

 更新字典,如若有3个字典A和B,A.update(B),A和B相同的键的值会被B更新,而B中尚无的键值对会被添加到A中

4858.com 3534858.com 354

  def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

View Code

 举个例子

4858.com 3554858.com 356

info = {
    'name':'Frank',
    'age':23,
    'hobby':'reading',
    'address':'Shanghai',
}
info_new = {
    'age':24,
    'hobby':'sleeping',
    'QQ':'110110',
}
info.update(info_new)
print(info)
#运行结果
{'name': 'Frank', 'age': 24, 'hobby': 'sleeping', 'address': 'Shanghai', 'QQ': '110110'}

View Code

 .copy()

 复制字典

4858.com 3574858.com 358

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
info_new = info.copy()
info['name']='Jack'
info['hobby'][0]='writing'
print(info)
print(info_new)
#运行结果
{'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}
{'name': 'Frank', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}

View Code

 我们会发觉和列表中的copy一样,也存在字典里面包车型地铁列表的成分被涂改后,复制的字典也会自动修改,那么些原因实在和后边的是同样的,大家那里也足以动用deep.copy

4858.com 3594858.com 360

import copy
info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
info_new = copy.deepcopy(info)
info['name']='Jack'
info['hobby'][0]='writing'
print(info)
print(info_new)
#运行结果
{'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'Shanghai'}

View Code

 那字典里的字典会不会出现相同的标题啊?

4858.com 3614858.com 362

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
    'language':{1:'Python',2:'Go'},
}
info_new = info.copy()
info['name']='Jack'
info['hobby'][0]='writing'
info['language'][2]='Java'
print(info)
print(info_new)
#运行结果
{'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}
{'name': 'Frank', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}

View Code

 答案是,是的,当大家想在改动原字典的时候,复制的字典保持不变,照旧得以应用deep.copy来消除那个标题。

4858.com 3634858.com 364

import copy
info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
    'language':{1:'Python',2:'Go'},
}
info_new = copy.deepcopy(info)
info['name']='Jack'
info['hobby'][0]='writing'
info['language'][2]='Java'
print(info)
print(info_new)
#运行结果
{'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Go'}}

View Code

 那也是我们常说的深浅copy!

.fromkeys()

 用来创立一个新的字典

4858.com 3654858.com 366

   def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass

View Code

 举个例证

4858.com 3674858.com 368

key = (1,2,3,4,5)
value = 'Python'
print(dict.fromkeys(key,value))
#运行结果
{1: 'Python', 2: 'Python', 3: 'Python', 4: 'Python', 5: 'Python'}

View Code

 .get()

 根据键重回值,未有键则重回None

4858.com 3694858.com 370

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
print(info.get('hobby'))
#运行结果
['reading', 'sleep']

View Code

 .items()

 返回dict_items(),1般结合for循环使用

4858.com 3714858.com 372

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
print(info.items())
#运行结果
dict_items([('name', 'Frank'), ('age', 23), ('hobby', ['reading', 'sleep']), ('address', 'Shanghai')])

View Code

4858.com 3734858.com 374

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
for k,v in info.items():
    print(k,"---",v)
#运行结果
name --- Frank
age --- 23
hobby --- ['reading', 'sleep']
address --- Shanghai

View Code

.popitem()

 弹出最后1个键值,会回来1个元组,当弹空字典会报错

4858.com 3754858.com 376

 def popitem(self): # real signature unknown; restored from __doc__
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

View Code

 举个例子

4858.com 3774858.com 378

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
print(info.popitem())
info.popitem()
print(info)
#举个例子
('address', 'Shanghai')
{'name': 'Frank', 'age': 23}

View Code

.setdefault(key,value)

假诺键在字典中,则赶回那个键的值,假使不在字典中,则向字典中插入这么些键,并回到value,暗许value位None
举个例证

4858.com 3794858.com 380

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
}
print(info.setdefault('name'))   #存在键name,返回值
print(info)
print(info.setdefault('address','shanghai'))  #不存在键address,返回'shanghai',添加键值对
print(info)
print(info.setdefault('QQ'))    #不存在键QQ,添加键QQ,返回None
print(info)
#运行结果
Frank
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep']}
shanghai
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'shanghai'}
None
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'shanghai', 'QQ': None}

View Code

 

前些天就写到那里了,欢迎各位大佬提议错误和不足之处,多谢了!

 

 

 3.angular.element()  应该用 directive

4858.com 3814858.com 382

 

4858.com 3834858.com 384

namespace Ptototype_Pattern
{
    class TestMain
    {
        static void Main(string[] args)
        {
            ReSume A = new ReSume("张三");
            A.SetPersonInfo("25","男","1988-10-10");
            A.SetWorkExperice("2010--2013", "X公司");

            ReSume B = (ReSume)A.Clone();
            B.SetWorkExperice("2009--2010", "Y公司");

            ReSume C = (ReSume)A.Clone();
            C.SetWorkExperice("2006--2009", "Z公司");

            A.Display();
            B.Display();
            C.Display();

            Console.ReadLine();

        }
    }
}

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <style>
        .a{color:red;}
    </style>
</head>
<body>
    <p>12345</p>
    <script>
        var p1=document.getElementsByTagName("p")[0];
        angular.element(p1).addClass('a');
    </script>
</body>
</html>

View Code

 

View Code

4858.com 385

 

 四. JSON.stringify()  // 对象转成string

 

 

4858.com 3864858.com 387

深复制和浅复制:MemberwiseClone 方法创造八个外面副本,方法是创办三个新对象,然后将日前目的的非静态字段复制到该新对象。 假诺字段是值类型的,则对该字段执行逐位复制。 如若字段是援引类型,则复制引用但不复制引用的靶子;因而,原始对象及其复本引用同一对象。

 

  <script>
        var a={a:1,b:2};
        console.log("xx: "+typeof a+" :"+a);
        var b=JSON.stringify(a);    // 转成string 类型
        console.log("x2x: "+typeof b+" :"+b);
    </script>

引用类型的例子如下:

View Code

新添加工作经历类(WorkExperice)

 伍.angular.extend(obj贰,obj一)  //
 把obj壹的属性复制给obj二并把结果赋值给obj二  

 

4858.com 3884858.com 389

4858.com 3904858.com 391

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script>
        var obj1={name:'tom'};
        var obj2={sex:'female'};
        var obj_new=angular.extend(obj2,obj1);    // 返回值赋给obj2
        console.log("obj1: "+JSON.stringify(obj1));
        console.log("obj2: "+JSON.stringify(obj2));
        console.log("obj_new: "+JSON.stringify(obj_new));
    </script>
namespace Ptototype_Pattern
{
    class WorkExperice
    {
        private string workTime;
        private string workCompany;
        /// <summary>
        /// 工作时间
        /// </summary>
        public string WorkTime
        {
            get { return workTime; }
            set { workTime = value; }
        }

        /// <summary>
        /// 工作企业
        /// </summary>
        public string WorkCompany
        {
            get { return workCompany; }
            set { workCompany = value; }
        }
    }
}

View Code

View Code

 陆. webStorm 智能提示jq angularjs语法

 

4858.com 392

简历类(Resume) :继承于系统的仿造接口(ICloneable)

 7.注脚 controllers 的推荐介绍的措施是使用数组表示法

4858.com 3934858.com 394

4858.com 395

namespace Ptototype_Pattern
{
    class ReSume:ICloneable
    {
        private string name;
        private string age;
        private string sex;
        private string birthday;
        //private string time;
        //private string company;
        private WorkExperice work;
        public ReSume(string name)
        {
            this.name = name;
            work = new WorkExperice();

        }

        /// <summary>
        /// 设置个人信息
        /// </summary>
        /// <param name="age"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        public void SetPersonInfo(string age, string sex, string birthday)
        {
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
        }

        /// <summary>
        /// 设置工作经历
        /// </summary>
        /// <param name="time"></param>
        /// <param name="company"></param>
        public void SetWorkExperice(string time, string company)
        {
            //this.time = time;
            //this.company = company;
            work.WorkTime = time;
            work.WorkCompany = company;

        }

        public void Display()
        {
            //Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            //Console.WriteLine("在 {0} 工作于 {1} \n",time,company);

            Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            Console.WriteLine("在 {0} 工作于 {1} \n", work.WorkTime, work.WorkCompany);

        }

        public Object Clone()
        {
            return (Object)this.MemberwiseClone();
        }
    }
}

8.angularjs.forEach()  angularjs.fromJson()

View Code

4858.com 3964858.com 397

客户端不变:(全为Z公司)

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script>
        /* 1. angularjs.forEach();  */
        var objs =[{a:1},{a:2}];
        angular.forEach(objs, function(data,index,array){
            //data等价于array[index]
            console.log(data.a+'='+array[index].a);
            console.log("xx: "+data.a);
        });
        /*  2.  angular.fromJson()  */
        var json='{"name":"haha","password":"321"}';
        var jsonStr=angular.fromJson(json);     //  把json转成对象
        console.log("jsonStr: "+typeof jsonStr);
        console.log("jsonStr name: "+jsonStr.name);
    </script>

4858.com 398

View Code

MemberwiseClone 方法创造贰个表皮副本,对于引用类型复制引用,但不复制引用的对象

 9. ng-class

改为深复制如下:

4858.com 3994858.com 400

干活经验类(WorkExperice)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .testCol{color:blue;}
        .testSize{font-size: 30px;}
        .testBorder{border: 1px solid red;}
        .red{color:red;}
    </style>
</head>

<body>
    <div ng-app="app" ng-controller="myCtrl">

    <p ng-class="{testCol:color,testSize:size,testBorder:border}">{{name}}</p>
                    <!--  属性是样式,值是true or false -->
        <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
        <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
        <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
        <input type="checkbox" ng-model="error"> error (apply "red" class)
        <hr>


        </div>
        <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
        <script>
            angular.module("app",[])
                .controller("myCtrl",["$scope", function ($scope) {
                     $scope.name='haha';
                        $scope.color=true;     /*  true 则应用该样式*/
                        $scope.size=false;
                        $scope.border=true;
                }])
        </script>
</body>
</html>

 

View Code

4858.com 4014858.com 402

 10.ng-copy 复制  ng-paste粘贴  ng-cut 剪切

namespace Ptototype_Pattern
{
    class WorkExperice:ICloneable
    {
        private string workTime;
        private string workCompany;
        /// <summary>
        /// 工作时间
        /// </summary>
        public string WorkTime
        {
            get { return workTime; }
            set { workTime = value; }
        }

        /// <summary>
        /// 工作企业
        /// </summary>
        public string WorkCompany
        {
            get { return workCompany; }
            set { workCompany = value; }
        }

        public Object Clone()
        {
            return (object)this.MemberwiseClone();
        }
    }
}

4858.com 4034858.com 404

View Code

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>

</head>
<body>
<div ng-app="app" ng-controller="myCtrl">
        <div ng-bind="name"></div>
    <input type="text" ng-model="name" ng-copy="copy()"/>
    </div>
    <script>
        /*触发条件:复制。鼠标右键复制和快捷键Ctrl+C都会触发。*/  
        angular.module("app",[])
            .controller("myCtrl",["$scope", function ($scope) {
                 $scope.name='haha';
                    $scope.copy= function () {
                        alert(1);
                    }
            }])

    </script>
</body>
</html>

 

View Code

简历类(Resume) :继承于系统的克隆接口(ICloneable)

 11.ng-list

4858.com 4054858.com 406

4858.com 4074858.com 408

namespace Ptototype_Pattern
{
    class ReSume:ICloneable
    {
        private string name;
        private string age;
        private string sex;
        private string birthday;
        //private string time;
        //private string company;
        private WorkExperice work;
        public ReSume(string name)
        {
            this.name = name;
            work = new WorkExperice();

        }
        public ReSume(WorkExperice work)
        {
            this.work = (WorkExperice)work.Clone();
        }

        /// <summary>
        /// 设置个人信息
        /// </summary>
        /// <param name="age"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        public void SetPersonInfo(string age, string sex, string birthday)
        {
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
        }

        /// <summary>
        /// 设置工作经历
        /// </summary>
        /// <param name="time"></param>
        /// <param name="company"></param>
        public void SetWorkExperice(string time, string company)
        {
            //this.time = time;
            //this.company = company;
            work.WorkTime = time;
            work.WorkCompany = company;

        }

        public void Display()
        {
            //Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            //Console.WriteLine("在 {0} 工作于 {1} \n",time,company);

            Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            Console.WriteLine("在 {0} 工作于 {1} \n", work.WorkTime, work.WorkCompany);

        }

        public Object Clone()
        {
            //return (Object)this.MemberwiseClone();
            ReSume resum = new ReSume(this.work);
            resum.name = this.name;
            resum.age = this.age;
            resum.birthday = this.birthday;
            return resum;
        }
    }
}
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="myCtrl">
    <p>ng-list自定义输入数组   a.b.c.d </p>
    <input type="text" ng-model="lists" ng-list="."/><br/>
    {{lists}}
    <li ng-repeat="list in lists">{{list}}</li>
    </div>
    <script>
        angular.module("app",[])
            .controller("myCtrl",["$scope", function ($scope) {
                $scope.lists=['a','b','c'];
            }])
    </script>
</body>
</html>

View Code

View Code

客户端不变:

 12. angular 获得input的值

4858.com 409

4858.com 4104858.com 411

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
  <!--<script src="http://apps.bdimg.com/libs/angular.js/1.5.3/angular.min.js"></script>-->
  <script src="//cdn.bootcss.com/angular.js/1.5.3/angular.min.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="myCtrl">
<input type="text" ng-model="orderNum"/>
  <button ng-click="check()">btn</button>
</div>
<script>
  angular.module("app",[])
    .controller("myCtrl", function ($scope) {
      $scope.check= function () {
         alert($scope.orderNum)
      }
    })
</script>
</body>
</html>

 

View Code

 

 13.angular factory service

 

4858.com 4124858.com 413

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
  <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="appTest" ng-controller="MyController">
<ul>
  <li ng-repeat="test in tests">
    id: {{test.id}} 名字: {{test.name}}
    信息: {{test.lastText}}
    <button ng-click="remove(test)">delete</button>
  </li>
</ul>
</div>
<script>
  var appTest = angular.module("appTest",[]);
  appTest.factory("myFactory", function () {
      var f={};
      f.remove= function (arr,item) {
        return arr.splice(arr.indexOf(item),1);
      }
      return f;
    });
  appTest.service("myService", function (myFactory) {
      this.remove=function(arr,item){
        return myFactory.remove(arr,item);
      }
    });
  appTest.controller("MyController", function ($scope,$http,myService) {
      $http.get("test.json").success(function (data) {
        $scope.tests=data;
      });
      //    把factory service 删除,直接在控制器中可以实现删除效果
      /* $scope.remove= function (test) {
       $scope.tests.splice($scope.tests.indexOf(test),1);
       }*/
      $scope.remove= function (test) {
         myService.remove($scope.tests,test);
      }
    });
</script>

</body>
</html>

 

View Code

14.angular 指令(1)

4858.com 4144858.com 415

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body ng-app="app">
  <hello-word>12345</hello-word>
  <hello-word></hello-word>
  <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
  <script>
    angular.module("app",[])
      .directive('helloWord', function () {
        return{
          restrict:'E',    //  E 元素  A 属性
          template:'<div>hi, how are yousss<br/></div>',
          replace:true,    /* 隐藏 <hello-word>标签 */
          transclude:true     /* 保留 标签里面的内容: 12345 */
        }
      })
  </script>
</body>
</html>

View Code

15.anguar 指令 link

4858.com 4164858.com 417

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
  <style>
    .expander {
      border: 1px solid black;
      width: 250px;
    }

    .expander>.title {
      background-color: black;
      color: white;
      padding: .1em .3em;
      cursor: pointer;
    }

    .expander>.body {
      padding: .1em .3em;
    }
  </style>
</head>
<body ng-app="expanderModule">
<div ng-controller='SomeController'>
  <expander class='expander' expander-title='title'>
    {{text}}
  </expander>

</div>
  <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
  <script>
    var expanderModule=angular.module('expanderModule', [])
    expanderModule.directive('expander', function() {
      return {
        restrict : 'EA',
        replace : true,
        transclude : true,
        scope : {
          title : '=expanderTitle'
        },
        template : '<div>'
        + '<div class="title" ng-click="toggle()">{{title}}</div>'
        + '<div class="body" ng-show="showMe" ng-transclude></div>'
        + '</div>',
        link : function(scope, element, attrs) {
          scope.showMe = false;
          scope.toggle = function toggle() {
            scope.showMe = !scope.showMe;
          }
        }
      }
    });
    expanderModule.controller('SomeController',function($scope) {
      $scope.title = '点击展开';
      $scope.text = '这里是内部的内容。';
    });
  </script>
</body>
</html>

View Code

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有