美文网首页
Python基础

Python基础

作者: 投降又不会赢 | 来源:发表于2017-08-16 21:19 被阅读18次

Python 基础

使用环境:
**mac **
pycharm
python2.7

可以看到的内容如下:

函数 私有性 超类 多重继承

函数

repr 函数返回本质的字符串或者其他对象

print repr('123')
# 输出为:   '123' 

print repr([1,2,3])
#输出为 [1,2,3]

lambda函数 匿名函数


def sq(x):
    return x * x

lambda x: x * x

#上面两个函数意义相同

callable(getattr(tc, 'funcname')) 查看某个类是否含有某个方法

注意在python3中该方法已不再可用,可以使用hasattr(x,'call')方法


callable(getattr(talk,'mouth'))
# 会输出True False 

super()

super(class,self).init() 类似于OC中的[super init]方法
可以保持超类的属性和值 或方法


__metaClass__  = type

class Bird:
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry :
            print "Aaaah..."
            self.hungry = False
        else:
            print "NO, Thanks"


class    SongBird(Bird):
    def __init__(self):
        super(SongBird, self).__init__()
        self.sound = 'Squawk'
    def sing(self):
        print self.sound

set的union()
a = set([1, 2, 3])
b = set([2,3,4])
a.union(b) 或者 a|b 结果都为set([1, 2, 3, 4])

创建类:


# _*_coding:utf8_*_
# 上一句声明编码类型

__metaClass__ = type # 确定使用新式类
# 创建一个Person 类
class Person:
    def setName(self,name):
        self.name = name
    def getName(self):
        return self.name
    def greet(self):
        print "Hello World! I'm is %s" % self.name
        
        
# 调用

foo = Person()
bar = Person()
foo.setName('liLei')
bar.setName('hanMeiMei')
print foo.getName()
print bar.getName()

foo.greet()
bar.greet()

如果知道foo 是Person的实例的话 还可以Person.getName(foo) 这样调用

私有性

为了将方法或者特征变为私有,只要在它名字的前面加上双下划线即可

**代码示例: **

# _*_coding:utf8 _*_

__metaClass__ = type
class privateClass:
    def __privateFunc(self);
        print "I'm a private function"

    def printPrivateFunc(self):
        print "private function is :"
        self.__privateFunc()

前面有下划线的名字不会被带星号的import语句**from privateClass import * ** 导入

超类

class SPAMFilter(Filter): Filter为SPAMFilter的超类

过滤的例子:


# _*_ coding:utf8 _*_

__metaClass__ = type

class Filter:
    def init(self):
        self.blocked = []
    def filter(self, sequence):
        return [x for x in sequence if x not in self.blocked]

class SPAMFilter(Filter):
    def init(self): # 重写超类的init方法
        self.blocked = ['SPAM']



s = SPAMFilter()
s.init()

print s.filter(['SPAM', 'SPAM', 'SPAM', 'SPAM', 'back', 'bacon'])
# 输出为 ['back', 'bacon']

**[x for x in sequence if x not in self.blocked] **等价于


 lst = []
 for x in sequence:
    if x not in self.blocked:
        lst.append(x)

如果想要查看一个类是否是另外一个类的子类,可以使用issubclass内建函数

print issubclass(SPAMFilter,Filter)
#输出为True

print issubclasss(Filter,SPAMFilter)
#输出为False

如果想要知道已知类的基类(超类)们,可以使用它的特殊特性 bases

print SPAMFilter.__bases__

可以使用**isinstance **方法检查一个对象是否是一个类的实例

s = SPAMFilter()
print isinstance(s, SPAMFilter)
#输出 True

print isinstance(s,Filter)
#输出True

print isinstance(s,str)
#输出False

多重继承

python中的类可以继承多个基类

例如:


class Calculator:
    def calculate(self, expression):
        self.value = eval(expression)

class Talker:
    def talk(self):
        print "Hi, my value is ", self.value

# 继承于Calculator  和 Talker 
class TalkCaculator(Calculator, Talker):
    pass


tc = TalkCaculator()
tc.calculate('1+2*3')
print tc.talk()

当使用多重继承的时候 有个注意点

当继承的超类都含有相同名字的不同方法,那么必须要注意一下超类的顺序,先继承的超类会重写后继承的类中的方法。如果Calculator 和 Talker都有talk方法 则Calculator会重写Talker的talk方法 使其不能访问,如果把他们的顺序倒过来就会让Talker的talk方法可以访问了。

静态方法和类成员方法

使用@操作符,在方法(或者函数)的上方将装饰器列出、从而指定一个或者更多的装饰器(**多个装饰器在应用时的顺序与指定顺序相反 **)

例子:

__metaClass__ = type
class MyClass:
    @staticmethod
    def smeth():
        print 'This is a static method'

    @classmethod
        def cmeth(cls):
            print 'This is a class method ', cls

# 调用
MyClass.smeth()
MyClass.cmeth()
# 输出
'''
This is a static method
This is a class method of  __main__.MyClass
'''

属性

property 函数的使用


# _*_ coding:urf8 _*_

__metaClass__ = type


class Rectangle:
    self.width = 0
    self.height = 0
    
def setSize(self,size):
    self.width, self.height = size

def getSize(self):
    return self.width, self.height

size = self.width, self.height


r = Rectangle()
r.width = 10
r.height = 5
print r.size

#输出为 (10,5)

getattrsetattr、和它的朋友们

拦截对象的所有属性访问是可能的,这样可以使用旧式类实现属性。为了访问属性的时候可以执行代码,必须使用一些魔法(特殊)方法。下面4中方法提供了需要的功能(在旧式类中只需要后三个)

  • getattribute(self, name) :当属性name被访问时自动被调用
  • getattr(self,name): 当特征name被访问且对象没有相应的特征时被自动调用。
  • setattr(self,name,value) :当视图给属性name赋值时会被自动调用
  • delattr(self,name):当视图删除属性name时会被自动调用

** 示例**

# _*_coding:utf8_*_ 

__metaClass__ = type

class Rectangle:
    def __init__(self):
        self.width = 0
        self.height = 0
    
    def __setattr__(self, key, value):
        if key == 'size':
            self.width, self.height = value
        else:
            self.__dic__[key] = value
    
    def __getattr__(self, item):
        if item == 'size':
            return self.width, self.height
        else:
            raise AttributeError

self.dic 该方法包含一个字典。字典里面是实例的所有属性 。

相关文章

网友评论

      本文标题:Python基础

      本文链接:https://www.haomeiwen.com/subject/onswrxtx.html