0
点赞
收藏
分享

微信扫一扫

python杂记——内置函数(八)

慕容冲_a4b8 2022-04-13 阅读 108

@staticmethod

@staticmethod,将一个方法转换为静态方法。静态方法不接收隐式的第一个参数,也就是用于指定实例的self。静态函数可以通过类(例如: C.f())或者实例(C().f())来调用。像所有装饰器一样,也可以将 staticmethod 作为常规函数调用,并对其结果做进一步操作。

测试代码:

def test_staticmethod():
    class C:
        @staticmethod
        def add(x, y):
            return x + y
        
        def sub(x, y):
            return x - y
        
        sub_s = staticmethod(sub)
    print("called by class: ", C.add(11, 23))
    print("called by instance: ", C().add(23, 34))
    
    print("called by class: ", C.sub_s(33, 23))
    print("called by instance: ", C().sub_s(57, 34))
test_staticmethod()

测试结果:

called by class:  34
called by instance:  57
called by class:  10
called by instance:  23

str

class str(object=‘’),class str(object=b’', encoding=‘utf-8’, errors=‘strict’),将对象转换为适合人阅读的形式。如果没有指定encodeing和errors参数,则会调用object的__str__方法并返回结果,对于字符串则返回字符串本身,如果object没有__str__方法则返回repr(object)的结果。如果指定了encoding或者errors其中一个则object应该是类似字节的对象(例如bytes或bytearray)。

测试代码:

def test_str():
    class WithStr:
        def __str__(self):
            return "this is class with str method"
    class WithRepr:
        def __repr__(self):
            return "this class with repr"

    class WithoutStr:
        def f():
            return
        
    print("str('test string'): ", str("test string"))
    print("str(): ", str())
    
    print("str(WithStr): ", str(WithStr()))
    print("str(WithRepr: ", str(WithRepr()))
    print("str(WithoutStr: ", str(WithoutStr()))
test_str()

测试结果:

str('test string'):  test string
str():  
str(WithStr):  this is class with str method
str(WithRepr:  this class with repr
str(WithoutStr:  <__main__.test_str.<locals>.WithoutStr object at 0x7f4784be7e50>

sum

sum(iterable[, start]),返回iterable的和然后再加上start的值,iterable一般是数字,start不允许是字符串。有些情况有其他方法可以替代sum。连接字符串序列的首选快速方法是调用 ‘’.join(sequence)。 要添加具有扩展精度的浮点值,请参阅 math.fsum()。 要连接一系列可迭代对象,请考虑使用 itertools.chain()。

测试代码:

def test_sum():
    l1 = [1, 2, 3, 4, 5, 6, 7]
    print("sum(l1):", sum(l1))
    print("sum(l1, 3): ", sum(l1, 3))
test_sum()

测试结果:

sum(l1): 28
sum(l1, 3):  31

super

super([type[, object-or-type]]),该方法用于调用在类中已重写的继承方法非常有用。MRO属性就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
如果省略第二个参数,则返回的超级对象是未绑定的。如果第二个参数是对象,则 isinstance(obj, type) 必须为真。如果第二个参数是一个类型,issubclass(type2, type) 必须为真(这对类方法很有用)。
super有两种典型应用场景,第一种是在具有单继承的类层次结构中,可以使用 super 来引用父类而无需显式命名它们,从而使代码更易于维护。这种用法与在其他编程语言中使用 super 非常相似。第二中是动态执行环境中的多重继承,这种情况是python独有的,其他静态编译语言或者仅支持单继承的语言中没有。这就可能出现钻石继承,要解决不管任何时候调用的函数都会相同的问题(因为调用的顺序是在运行时确定的,因为该顺序会适应类层次结构的变化,并且因为该顺序可以包括在运行前未知的兄弟类)。

Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx。
测试代码:

def test_super():
    class A:
        def __init__(self):
            print("A init called")
    class C:
        def __init__(self):
            print("C init called")    
    class B(A):
        def __init__(self):
            super().__init__()
            print("B init called")
    class D(A, C):
        def __init__(self):
            super().__init__()
            C.__init__(self)
            print("D init called")
    
    b = B()
    print("b.mro: ", B.mro())
    d = D()
    print("d.mro: ", D.mro())
test_super()

测试结果:

A init called
B init called
b.mro:  [<class '__main__.test_super.<locals>.B'>, <class '__main__.test_super.<locals>.A'>, <class 'object'>]
A init called
C init called
D init called
d.mro:  [<class '__main__.test_super.<locals>.D'>, <class '__main__.test_super.<locals>.A'>, <class '__main__.test_super.<locals>.C'>, <class 'object'>]

tuple

class tuple([iterable]),tuple实际上不是一个函数,而是一个不可变的序列类型。 tuple() 函数将列表转换为元组。

测试代码:

def test_tuple():
    l1 = [1, 2, 3, 4, 5, 6, 7]
    print("tuple(l1): ", tuple(l1))
    
    d1 = {"one": 1, "two": 2, "three": 3}
    print("tuple(d1): ", tuple(d1))
    
    s1 = "hello world"
    print("tuple(s1): ", tuple(s1))
test_tuple()

测试结果:

tuple(l1):  (1, 2, 3, 4, 5, 6, 7)
tuple(d1):  ('one', 'two', 'three')
tuple(s1):  ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')

vars

vars([object]),返回模块、类、实例或任何其他具有__dict__属性的对象的__dict__属性。
模块和实例等对象的 _dict_ 属性是可修改的; 其他对象可能对其 _dict_ 属性有写入限制(例如,类使用 types.MappingProxyType 来防止直接字典更新)。
如果没有参数,vars() 的行为就像 locals()。 请注意,本地字典仅对读取有用,因为本地字典的更新被忽略。

测试代码:

def test_vars():
    print("vars(): ", vars())

    class A:
        def __init__(self):
            self.num = 1
            self.name = "A"
            print("A init function")

    print("vars(A): ", vars(A))
    a = A()
    print("vars(a): ", vars(a))
test_vars()

测试结果:

vars():  {}
vars(A):  {'__module__': '__main__', '__init__': <function test_vars.<locals>.A.__init__ at 0x7f311e945a70>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
A init function
vars(a):  {'num': 1, 'name': 'A'}

zip

zip(*iterables),将iterables中的元素整合到一起,创建一个tuple迭代器并返回。其中第i个元素是iterables中对应的第i个元素的合集。当最少的iterable访问结束后迭代器停止。保证迭代访问的顺序是从左到右的。

测试代码:

def test_zip():
    l1 = [1, 2, 3, 4, 5, 6]
    l2 = ["one", "two", "three", "four"]
    z1 = zip(l1, l2)
    print("type(z1): ", type(z1), "; value: ", list(z1))
    
    l3, l4 = zip(*zip(l1, l2))
    print("l3: ", l3, "; l4: ", l4)

    z2 = zip((l1, l2)*3)
    print("type(z2): ", type(z2), "; value: ", list(z2))
test_zip()

测试结果:

type(z1):  <class 'zip'> ; value:  [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
l3:  (1, 2, 3, 4) ; l4:  ('one', 'two', 'three', 'four')
type(z2):  <class 'zip'> ; value:  [([1, 2, 3, 4, 5, 6],), (['one', 'two', 'three', 'four'],), ([1, 2, 3, 4, 5, 6],), (['one', 'two', 'three', 'four'],), ([1, 2, 3, 4, 5, 6],), (['one', 'two', 'three', 'four'],)]

__import__

__import__(name, globals=None, locals=None, fromlist=(), level=0),函数用于动态加载类和函数 。如果一个模块经常变化就可以使用 __import__() 来动态载入。该函数导入模块名称,可能使用给定的全局变量和局部变量来确定如何在包上下文中解释名称。 fromlist 给出了应该从 name 给定的模块导入的对象或子模块的名称。标准实现根本不使用它的 locals 参数,并且只使用它的 globals 来确定 import 语句的包上下文。

level 指定是使用绝对导入还是相对导入。 0(默认值)表示只执行绝对导入。 level 的正值表示相对于调用 import() 的模块的目录要搜索的父目录的数量(有关详细信息,请参阅 PEP 328)。

当 name 变量的形式为 package.module 时,通常会返回顶级包(直到第一个点的名称),而不是按名称命名的模块。但是,当给定非空 fromlist 参数时,将返回按名称命名的模块。

这个就不再举具体的例子了。

举报

相关推荐

0 条评论