zoukankan      html  css  js  c++  java
  • 获取属性以及基本方法

    静态语言 vs 动态语言
    对于静态语言(例如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或者它的子类,否则,
    将无法调用run()方法。
    对于Python这样的动态语言来说,则不一定需要传入Animal类型。我们只需要保证传入的对象有一个run()方法就可以
    了。

    Python的“file-like object“就是一种鸭子类型。对真正的文件对象,它有一个read()方法,返回其内容。但是,许多对
    象,只要有read()方法,都被视为“file-like object“。许多函数接收的参数就是“file-like object“,你不一定要传入真正的文
    件对象,完全可以传入任何实现了read()方法的对象

    type() :获取对象类型

    >>> type(123)
    <class 'int'>
    >>> type('str')
    <class 'str'>
    >>> type(None)
    <type(None) 'NoneType'>

    isinstance():判断对象和类型关系,也可判断基本类型

    >>> a = Animal()
    >>> d = Dog()
    >>> h = Husky()
    >>> isinstance(h, Husky)
    >>> isinstance(h, Animal)
    >>> isinstance('a', str)
    True
    >>> isinstance(123, int)
    True
    >>> isinstance(b'a', bytes)
    >>> isinstance([1, 2, 3], (list, tuple))
    True
    >>> isinstance((1, 2, 3), (list, tuple))

    dir():获取一个对象所有属性和方法

    >>> dir('ABC')

    getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态:

    >>> hasattr(obj, 'x') # 有属性'x'吗?
    True
    >>> obj.x
    9 >>> hasattr(obj, '
    y') #
    有
    属
    性
    '
    y'
    ?
    False
    >>> setattr(obj, 'y', 19) # 设置一个属性'y'
    >>> hasattr(obj, 'y') # 有属性'y'吗?
    True
    >>> getattr(obj, 'y') # 获取属性'y'
    19
    >>> obj.y # 获取属性'y'
  • 相关阅读:
    Codeforces Round #592 (Div. 2)C. The Football Season(暴力,循环节)
    Educational Codeforces Round 72 (Rated for Div. 2)D. Coloring Edges(想法)
    扩展KMP
    poj 1699 Best Sequence(dfs)
    KMP(思路分析)
    poj 1950 Dessert(dfs)
    poj 3278 Catch That Cow(BFS)
    素数环(回溯)
    sort与qsort
    poj 1952 buy low buy lower(DP)
  • 原文地址:https://www.cnblogs.com/dynas/p/6785162.html
Copyright © 2011-2022 走看看