参考:获取对象信息

NOTE

1.type()函数可以用来判断对象的类型:

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

如果一个变量指向函数或者类,也可以用type()判断.

也可以用来判断两个变量的类型是否相等:

>>> type(abs)==type(123)
False
>>> type('B')==type('H')
True

判断一个对象是否为函数:

>>> import types
>>> def f():
... pass
...
>>> type(f)==types.FunctionType
True
>>> type(abs)==types.BuiltinFunctionType
True
>>> type(lambda x: x)==types.LambdaType
True
>>> type((x for x in range(10)))==types.GeneratorType
True

2.isinstance():可以用来判断一个对象是否是某一个类的对象

#!/usr/bin/env python3

class Animal(object):
"""docstring for Animal"""
def __init__(self):
self.name = 'animal'
def run(self):
print('animal run')
def getname(self):
print(self.name) class Dog(Animal):
"""docstring for Dog"""
def __init__(self):
self.name = 'Dog'
def run(self):
print('dog run')
def getname(self):
print(self.name) def main():
a = Animal()
b = Dog() if isinstance(a, Animal):
print('a is animal')
if isinstance(b, Animal):
print('b is animal')
if isinstance(a, Dog):
print('a is dog')
if isinstance(b, Dog):
print('b is dog') if __name__ == '__main__':
main()
sh-3.2# ./oop5.py
a is animal
b is animal
b is dog

能够用type()函数判断的类型,也可以用isinstance()判断。

3.如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list:

>>> dir('A')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法。

len('ABC') <=> 'ABC'.__len__()

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

#!/usr/bin/env python3

class MyClass(object):
"""docstring for MyClass"""
def __init__(self, name):
super(MyClass, self).__init__()
self.name = name
def getname(self):
print(self.name) def main():
me = MyClass('chen')
me.getname() # get object attribute if hasattr(me, 'name'):
print('me have attr name')
getattr(me, 'name')
if hasattr(me, 'age'):
print('me have attr age')
getattr(me, 'age')
print('first judge finished') setattr(me, 'age', 20) if hasattr(me, 'age'):
print('me have attr age')
getattr(me, 'age')
print('second judge finished') # get object function
f = getattr(me, 'getname')
f() if __name__ == '__main__':
main()

注意,在这三个函数中,提供的均为属性名称。

sh-3.2# ./oop6.py
chen
me have attr name
first judge finished
me have attr age
second judge finished
chen

2017/2/27

Python学习札记(三十四) 面向对象编程 Object Oriented Program 5的更多相关文章

  1. Python学习札记(三十九) 面向对象编程 Object Oriented Program 10

    参考:使用枚举类 NOTE #!/usr/bin/env python3 from enum import Enum def main(): Mouth = Enum('Mouth', ('Jan', ...

  2. Python学习札记(三十八) 面向对象编程 Object Oriented Program 9

    参考:多重继承 NOTE #!/usr/bin/env python3 class Animal(object): def __init__(self, name): self.name = name ...

  3. Python学习札记(三十六) 面向对象编程 Object Oriented Program 7 __slots__

    参考:slots NOTE 1.动态语言灵活绑定属性及方法. #!/usr/bin/env python3 class MyClass(object): def __init__(self): pas ...

  4. Python学习札记(三十五) 面向对象编程 Object Oriented Program 6

    参考:实例属性和类属性 NOTE Python是动态语言,根据类创建的实例可以任意绑定属性. class Student(object): def __init__(self, name): self ...

  5. Python学习札记(三十二) 面向对象编程 Object Oriented Program 3

    参考:访问限制 NOTE 1.eg. #!/usr/bin/env python3 class Student(object): """docstring for Stu ...

  6. Python学习札记(二十四) 函数式编程5 返回函数

    参考:返回函数 NOTE 1.高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回. eg.求和函数 #!/usr/bin/env python3 def calsums(*args): a ...

  7. Python学习札记(三十) 面向对象编程 Object Oriented Program 1

    参考:OOP NOTE 1.面向对象编程--Object Oriented Programming,简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数. ...

  8. Python学习札记(四十) 面向对象编程 Object Oriented Program 11

    参考:使用元类 NOTE: type() 1.type()函数可以用于检查一个类或者变量的类型. #!/usr/bin/env python3 class Myclass(object): " ...

  9. Python学习札记(三十七) 面向对象编程 Object Oriented Program 8 @property

    参考:@property NOTE 1.在绑定参数时,为了避免对属性不符合逻辑的操作,需要对传入的参数进行审核. #!/usr/bin/env python3 class MyClass(object ...

随机推荐

  1. 生命游戏/Game of Life的Java实现

    首先简单介绍一下<生命游戏> 生命游戏其实是一个零玩家游戏.它包括一个二维矩形世界,这个世界中的每个方格居住着一个活着的或死了的细胞.一个细胞在下一个时刻生死取决于相邻八个方格中活着的或死 ...

  2. 【BZOJ1040】[ZJOI2008]骑士 树形DP

    [BZOJ1040][ZJOI2008]骑士 Description Z国的骑士团是一个很有势力的组织,帮会中汇聚了来自各地的精英.他们劫富济贫,惩恶扬善,受到社会各界的赞扬.最近发生了一件可怕的事情 ...

  3. .net Asp AdRotator(广告控件)

    1.新建项目名称AdRotator 2.右键项目名称添加一个xml文件命名为AdRotator.xml <?xml version="1.0" encoding=" ...

  4. Scala 泛型类型和方法

    abstract class Stack[A] { def push(x: A): Stack[A] = new NonEmptyStack[A](x, this) def isEmpty: Bool ...

  5. postgresql----SELECT

    示例1.简单查询 使用*查询表所有的字段,也可以指定字段名查询 test=# select * from tbl_insert; a | b ---+---- | sd | ff ( rows) te ...

  6. Laravel 5.7 No 'Access-Control-Allow-Origin' header is present on the request resource

    前后端项目跨域访问时会遇到此问题,解决方法如下: 创建一个中间件 php artisan make:middleware EnableCrossRequestMiddleware 该中间件的文件路径为 ...

  7. 编译安装基于nginx与lua的高性能web平台-openresty

    1.首先编译安装nginx(不多说) 2.开始安装openresty cd /usr/local/src wget https://openresty.org/download/openresty-1 ...

  8. CentOS7.2升级默认yum安装的php版本

    CentOS7.2yum安装php默认版本为5.4,可以升级通过yum安装更高版本 设置yum源 rpm -Uvh https://mirror.webtatic.com/yum/el7/webtat ...

  9. C#操作word之插入图片

    假如我们导出一份简历到word文档,那势必可能要同时导出我们包含的简历,下面就来试一下如何和通过C#代码,将图片插入到word文档中. 为了简便起见,就简单一点.类似下面这样的 姓名 张三 照片   ...

  10. C#实现像Git那样计算Hash值

    从Git Tip of the Week: Objects一文中得知,Git是这样计算提交内容的Hash值的: Hash算法用的是SHA1 计算前,会在内容前面添加"blob 内容长度\0& ...