built-in function

Built-Function

@abstractmethod 抽象方法,子类必须实现该方法
all(iterable)如果iterale里的元素都为true,返回true
ascii(object)返回object的str格式
bin(int)将一个整数转换为二进制字符串
callable(object)是否可调用

@classmethod 将一个方法转为类方法
一个类方法接收该类作为第一个方法参数,就像类实例方法一样,第一个参数接收的是类实例.通常用于对类属性进行操作

class C(object):
    count=0
    @classmethod
    def f(cls,t):
        print(t)
        cls.count+=1
        if( cls.count<10):
            cls.f(t=t)

delattr(object,name)等价于del object.name

dir()#列出当前工作空间包含的对象名称
dir(object),如果object本身有__dir__方法,那么实质上就是调用object.dir().如果没有,那么该方法就会去获得该object的__dict__属性.

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
dict(list(enumerate(seasons,start=1)))

compile可以把Python代码先赋值给某个变量,再特定时间场合通过eval或exec调用,运行这些Python代码
eval_code = compile( '1+2', '', 'eval')
eval(eval_code)
exec_code = compile( """for i in range(5):
... print "iter time: %d" % i""", '', 'exec' )
exec(exec_code)
scope={}#新的命名空间,作用域
exec()是执行一段代码,没有返回值,exec('a=1+1',scope)#创建了一个空间,运行结果是在scope空间里,而不是主空间,这样就不会破坏原有命名空间.
eval()是执行一个表达式,既然是表达式,就有返回值 比如a=eval('1+1')

filter(None,[1,2,0])#会把bool为False的值给过滤掉

float('inf'),float('nan')

format在字符串格式化这块非常强大
{}.format(*args)
'{name},{age}'.format(age=18,name='kzc')

globals():返回运行命令记录

hasattr(object,name)object是否有该属性
hash(object)返回object的hash值

hex(int)将一个整数转换乘十六进制字符串

iter(object),生成iterator

obejct没有__dict__,所以没法给object实例添加属性

oct(x)将整数转换为八进制字符串

ord(c)#给定一个unicode字符,返回其对应的整数

chr()

property

class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature
 
    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32
 
    def get_temperature(self):
        print("Getting value")
        return self._temperature
 
    def set_temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value
 
    temperature = property(get_temperature,set_temperature)


等价于
class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature
 
    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32
 
    @property
    def temperature(self):
        print("Getting value")
        return self._temperature
 
    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

c=Celsius()
c.temperature会嗲用get_temperature
c.temperature = 2 会调用set_temperature(2)

@staticmethod
将一个方法转换为静态方法,静态方法不仅类实例可以调用,类本身也可以调用

super

super工作原理
def super(cls, inst):#cls 代表类,inst 代表实例
    mro = inst.__class__.mro()    #获取 inst 的 MRO 列表
    return mro[mro.index(cls) + 1]
 """  查找 cls 在当前 MRO 列表中的 index, 并返回它的下一个类,即 mro[index + 1]"""


在类的继承中,如果重定义某个方法,该方法会覆盖父类的同名方法,但有时,我们希望能同时实现父类的功能,这时,我们就需要调用父类的方法,可以通过使用super来实现,
class Animal(object):
    def __init__(self, name):
        self.name = name
    def greet(self):
        print 'Hello, I am %s.' % self.name
 
class Dog(Animal):
    def greet(self):
        super(Dog, self).greet()   # Python3 可使用 super().greet()
        print 'WangWang...'
class Base(object):
    def __init__(self):
        print "enter Base"
        print "leave Base"
 
class A(Base):
    def __init__(self):
        print "enter A"
        super(A, self).__init__()
        print "leave A"
 
class B(Base):
    def __init__(self):
        print "enter B"
        super(B, self).__init__()
        print "leave B"
 
class C(A, B):
    def __init__(self):
        print "enter C"
        super(C, self).__init__()
        print "leave C"
        
C()
C.mro()#MRO(method resolution order),方法解析顺序
对于每一个类,Python会计算出一个方法解析顺序列表,它代表了类继承的顺序.



type(object) 通常等价于object.class
推荐使用isinstance().因为isinstance会考虑该object的子类

var(object),object.dict

zip(*iterables)返回一个每次从各迭代对象取一元素的迭代器

x=[1,2,3]
y=[4,5,6]
x2, y2 = zip(*zip(x, y))
list(x2)x and ylist(y2)

posted @ 2018-04-21 12:15  blog_hfg  阅读(173)  评论(0)    收藏  举报