流畅的python第一章总结

流畅的Python:

第一章总结:

  1. Python的特殊方法(以两个下划线开头,以两个下划线结尾,如__getitem__)。
  2. Card = collections.namedtuple('Card', ['rank', 'suit'])
    (需import collections)会创建一个只含属性不含方法的类,第一个参数为类名,第二个参数可以为有属性名组成的可迭代对象,也可以是有空格分隔开的字段名组成的字符串,如:
>>> from collections import namedtuple
>>> City = namedtuple('City', 'name country population coordinates')
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.321313, 139.1234324))
>>> tokyo
City(name='Tokyo', country='JP', population=36.933, coordinates=(35.321313, 139.1234324))
>>> tokyo.coordinates
(35.321313, 139.1234324)
>>> City._fields
('name', 'country', 'populatuon', 'coordinates')

_fields属性是一个包含这个类所有字段名称的元组

创建对象则为
beer_card = Card('7', 'diamonds')
beer_card为对象名,括号里的参数为属性的值。

  1. 从序列中随机选取一个元素:
    from random import choice
    choice(deck)
  2. abs函数:若输入为整数或者为浮点数,则返回绝对值,若输入为复数,则返回复数的模。
  3. Python内置函数repr,把一个对象用字符串的形式表达出来,它的特殊方法为__repr__。
  4. 算数运算符+和*的特殊方法为__add__和__mul__。
  5. bool函数的特殊方法为__bool__。
  6. from math import hypot
    hypot(x, y)
    返回欧几里得范数。

猜你喜欢

转载自blog.csdn.net/tlssnp/article/details/114263801