python FAE

1.python 时间戳用localtime转换时间戳较大时报错
ValueError: timestamp out of range for platform time_t
2.python面向对象编程


如何使用静态方法,类方法或者抽象方法?
方法是作为类的属性(attribute)存储的函数。你可以以下面的方式声明和获取函数:

class Pizza(object):
... def init(self, size):
... self.size = size
... def get_size(self):
... return self.size
...

Pizza.get_size

Python告诉你的是,类Pizza的属性get_size是一个非绑定的方法。这又指什么呢?很快我们就会知道,试着调用一下:

Pizza.get_size()
Traceback (most recent call last):
File "", line 1, in
TypeError: unbound method get_size() must be called with Pizza instance as first argument (got nothing instead)
这里我们不能调用这个方法是因为它没有被绑定到任一Pizza的实例上。一个方法需要一个实例作为它第一个参数(在Python 2中它必须是对应类的实例;在Python 3中可以是任何东西)。我们现在试试:

Pizza.get_size(Pizza(42))
42
现在可以了!我们试用一个实例作为get_size方法的第一个参数调用了它,所以一切变得很美好。但是你很快会同意,这并不是一个很漂亮的调用方法的方式;因为每次我们想调用这个方法都必须使用到类。并且,如果我们不知道对象是哪个类的实例,这种方式就不方便了。
所以,Python为我们准备的是,它将类Pizza的所有的方法绑定到此类的任何实例上。这意味着类Pizza的任意实例的属性get_size是一个已绑定的方法:第一个参数是实例本身的方法。

Pizza(42).get_size
<bound method Pizza.get_size of <main.Pizza object at 0x10314b310>>

Pizza(42).get_size()
42
如我们预期,现在不需要提供任何参数给get_size,因为它已经被绑定(bound),它的self参数是自动地设为Pizza类的实例。下面是一个更好的证明:

m = Pizza(42).get_size
m
<bound method Pizza.get_size of <main.Pizza object at 0x10314b350>>

m()
42
因此,你甚至不要保存一个对Pizza对象的饮用。它的方法已经被绑定在对象上,所以这个方法已经足够。
但是如何知道已绑定的方法被绑定在哪个对象上?技巧如下:

m = Pizza(42).get_size
m.self
<main.Pizza object at 0x10314b390>

m == m.self.get_size
True
易见,我们仍然保存着一个对对象的引用,当需要知道时也可以找到。

在Python 3中,归属于一个类的函数不再被看成未绑定方法(unbound method),但是作为一个简单的函数,如果要求可以绑定在对象上。所以,在Python 3中原理是一样的,模型被简化了。

class Pizza(object):
... def init(self, size):
... self.size = size
... def get_size(self):
... return self.size
...

Pizza.get_size
<function Pizza.get_size at 0x7f307f984dd0>
静态方法
静态方法是一类特殊的方法。有时,我们需要写属于一个类的方法,但是不需要用到对象本身。例如:
class Pizza(object):
@staticmethod
def mix_ingredients(x, y):
return x + y
def cook(self):
return self.mix_ingredients(self.cheese, self.vegetables)
这里,将方法mix_ingredients作为一个非静态的方法也可以work,但是给它一个self的参数将没有任何作用。这儿的decorator@staticmethod带来一些特别的东西:

Pizza().cook is Pizza().cook
False

Pizza().mix_ingredients is Pizza().mix_ingredients
True

Pizza().mix_ingredients is Pizza.mix_ingredients
True

Pizza()
<main.Pizza object at 0x10314b410>

Pizza()
<main.Pizza object at 0x10314b510>

Python不需要对每个实例化的Pizza对象实例化一个绑定的方法。绑定的方法同样是对象,创建它们需要付出代价。这里的静态方法避免了这样的情况:
降低了阅读代码的难度:看到@staticmethod便知道这个方法不依赖与对象本身的状态;
允许我们在子类中重载mix_ingredients方法。如果我们使用在模块最顶层定义的函数mix_ingredients,一个继承自Pizza的类若不重载cook,可能不可以改变混合成份(mix_ingredients)的方式。
类方法
什么是类方法?类方法是绑定在类而非对象上的方法!

class Pizza(object):
... radius = 42
... @classmethod
... def get_radius(cls):
... return cls.radius
...

Pizza.get_radius
<bound method type.get_radius of <class 'main.Pizza'>>

Pizza().get_radius
<bound method type.get_radius of <class 'main.Pizza'>>

Pizza.get_radius is Pizza().get_radius
False

Pizza.get_radius()
42
此处有问题。原文中

Pizza.get_radius is Pizza().get_radius
True
还需要check一下。
不管你如何使用这个方法,它总会被绑定在其归属的类上,同时它第一个参数是类本身(记住:类同样是对象)
何时使用这种方法?类方法一般用于下面两种:

  1. 工厂方法,被用来创建一个类的实例,完成一些预处理工作。如果我们使用一个@staticmethod静态方法,我们可能需要在函数中硬编码Pizza类的名称,使得任何继承自Pizza类的类不能使用我们的工厂用作自己的目的。
    class Pizza(object):
    def init(self, ingredients):
    self.ingredients = ingredients
    @classmethod
    def from_fridge(cls, fridge):
    return cls(fridge.get_cheese() + fridge.get_vegetables())
    静态方法调静态方法:如果你将一个静态方法分解为几个静态方法,你不需要硬编码类名但可以使用类方法。使用这种方式来声明我们的方法,Pizza这个名字不需要直接被引用,并且继承和方法重载将会完美运作。
    class Pizza(object):
    def init(self, radius, height):
    self.radius = radius
    self.height = height
    @staticmethod
    def compute_circumference(radius):
    return math.pi * (radius ** 2)
    @classmethod
    def compute_volume(cls, height, radius):
    return height * cls.compute_circumference(radius)
    def get_volume(self):
    return self.compute_volume(self.height, self.radius)

抽象方法
抽象方法在一个基类中定义,但是可能不会有任何的实现。在Java中,这被描述为一个接口的方法。
所以Python中最简单的抽象方法是:
class Pizza(object):
def get_radius(self):
raise NotImplementedError
任何继承自Pizza的类将实现和重载get_radius方法,否则会出现异常。这种独特的实现抽象方法的方式也有其缺点。如果你写一个继承自Pizza的类,忘记实现get_radius,错误将会在你使用这个方法的时候才会出现。

Pizza()
<main.Pizza object at 0x106f381d0>

Pizza().get_radius()
Traceback (most recent call last):
File "", line 1, in
File "", line 3, in get_radius
NotImplementedError
有种提前引起错误发生的方法,那就是当对象被实例化时,使用Python提供的abc模块。
import abc
class BasePizza(object):
metaclass = abc.ABCMeta
@abc.abstractmethod
def get_radius(self):
"""Method that should do something."""
使用abc和它的特类,一旦你试着实例化BasePizza或者其他继承自它的类,就会得到TypeError

BasePizza()
Traceback (most recent call last):
File "", line 1, in
TypeError: Can't instantiate abstract class BasePizza with abstract methods get_radius
混合静态方法、类方法和抽象方法
当我们构建类和继承关系时,终将会碰到要混合这些方法decorator的情况。下面提几个tip。
记住声明一个类为抽象类时,不要冷冻那个方法的prototype。这是指这个方法必须被实现,不过是可以使用任何参数列表来实现。
import abc
class BasePizza(object):
metaclass = abc.ABCMeta
@abc.abstractmethod
def get_ingredients(self):
"""Returns the ingredient list."""
class Calzone(BasePizza):
def get_ingredients(self, with_egg=False):
egg = Egg() if with_egg else None
return self.ingredients + egg
这个是合法的,因为Calzone完成了为BasePizza类对象定义的接口需求。就是说,我们可以把它当作一个类方法或者静态方法来实现,例如:
import abc
class BasePizza(object):
metaclass = abc.ABCMeta
@abc.abstractmethod
def get_ingredients(self):
"""Returns the ingredient list."""
class DietPizza(BasePizza):
@staticmethod
def get_ingredients():
return None
这样做同样争取,并且完成了与BasePizza抽象类达成一致的需求。get_ingredients方法不需要知道对象,这是实现的细节,而非完成需求的评价指标。
因此,你不能强迫抽象方法的实现是正常的方法、类方法或者静态方法,并且可以这样说,你不能。从Python 3开始(这就不会像在Python 2中那样work了,见issue5867),现在可以在@abstractmethod之上使用@staticmethod和@classmethod了。
import abc
class BasePizza(object):
metaclass = abc.ABCMeta
ingredient = ['cheese']
@classmethod
@abc.abstractmethod
def get_ingredients(cls):
"""Returns the ingredient list."""
return cls.ingredients
不要误解:如果你认为这是强迫你的子类将get_ingredients实现为一个类方法,那就错了。这个是表示你实现的get_ingredients在BasePizza类中是类方法而已。
在一个抽象方法的实现?是的!在Python中,对比与Java接口,你可以在抽象方法中写代码,并且使用super()调用:
import abc
class BasePizza(object):
metaclass = abc.ABCMeta
default_ingredients = ['cheese']
@classmethod
@abc.abstractmethod
def get_ingredients(cls):
"""Returns the ingredient list."""
return cls.default_ingredients
class DietPizza(BasePizza):
def get_ingredients(self):
return ['egg'] + super(DietPizza, self).get_ingredients()
Not_GOD(简书作者)
原文链接:http://www.jianshu.com/p/880d6a3ffdde

3.Traceback (most recent call last):
File "intraday.py", line 81, in
StockData.to_csv(Filename)
TypeError: to_csv() takes exactly 1 argument (2 given)

import urllib,time,datetime
import pandas as pd
from pandas import DataFrame
import pandas.io.data
import csv

class Quote(object):

DATE_FMT = '%Y-%m-%d'
TIME_FMT = '%H:%M:%S'

def init(self):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))

def append(self,dt,open_,high,low,close,volume):
self.date.append(dt.date())
self.time.append(dt.time())
self.open_.append(float(open_))
self.high.append(float(high))
self.low.append(float(low))
self.close.append(float(close))
self.volume.append(int(volume))

def to_csv(self):
return ''.join(["{0},{1},{2},{3:.2f},{4:.2f},{5:.2f},{6:.2f},{7} ".format(self.symbol,
self.date[bar].strftime('%Y-%m-%d'),self.time[bar].strftime('%H:%M:%S'),
self.open_[bar],self.high[bar],self.low[bar],self.close[bar],self.volume[bar])
for bar in xrange(len(self.close))])

def write_csv(self,filename):
with open(filename,'w') as f:
f.write(self.to_csv())

def read_csv(self,filename):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
for line in open(filename,'r'):
symbol,ds,ts,open_,high,low,close,volume = line.rstrip().split(',')
self.symbol = symbol
dt = datetime.datetime.strptime(ds+' '+ts,self.DATE_FMT+' '+self.TIME_FMT)
self.append(dt,open_,high,low,close,volume)
return True

def repr(self):
return self.to_csv()

class GoogleIntradayQuote(Quote):
''' Intraday quotes from Google. Specify interval seconds and number of days '''
def init(self,symbol,interval_seconds=300,num_days=5):
super(GoogleIntradayQuote,self).init()
self.symbol = symbol.upper()
url_string = "http://www.google.com/finance/getprices?q={0}".format(self.symbol)
url_string += "&i={0}&p={1}d&f=d,o,h,l,c,v".format(interval_seconds,num_days)
csv = urllib.urlopen(url_string).readlines()
for bar in xrange(7,len(csv)):
if csv[bar].count(',')!=5: continue
offset,close,high,low,open_,volume = csv[bar].split(',')
if offset[0]=='a':
day = float(offset[1:])
offset = 0
else:
offset = float(offset)
open_,high,low,close = [float(x) for x in [open_,high,low,close]]
dt = datetime.datetime.fromtimestamp(day+(interval_seconds*offset))
self.append(dt,open_,high,low,close,volume)

if name == 'main':
q = GoogleIntradayQuote
RUS3000 = []
with open('RUS3000.csv','rb') as f:
reader=csv.reader(f)
for row in reader:
RUS3000.extend(row)

for Ticker in RUS3000:
Filename = Ticker+'.csv'
StockData = q(Ticker,60,1)
print StockData
StockData.to_csv(Filename)

Execting StockData.to_csv(Filename) results in passing two arguments to def to_csv(self):. One self and the other is Filename. Shouldn't it be StockData.write_csv(Filename)?

原文地址:https://www.cnblogs.com/ITniu/p/7340879.html