擷取對象類型:
一、type
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name, score):
self.name = name
self.score = score
def run(self):
print 'Animal is run'
class Dog(Animal):
def run(self):
print 'Dog is run'
print type(dog.run)

print type(Animal)
import types #導入子產品types
print type('abc')==types.StringType #判斷'abc'是否為字元串類型
print type(u'abc')==types.UnicodeType
print type([])==types.ListType
print type(int)==type(str)==types.TypeType #所有的類型都是TypeType
二、isinstance類型
對于繼承關系class,用isinstance最為友善。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name, score):
self.name = name
self.score = score
def run(self):
print 'Animal is run'
class Dog(Animal):
def run(self):
print 'Dog is run'
print isinstance(dog, Dog) and isinstance(dog, Animal)
三、attr類型
- getattr()
-
(object, name[, default])¶getattr
- Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example,
getattr(x,
is equivalent to'foobar')
. If the named attribute does not exist, default is returned if provided, otherwisex.foobar
AttributeError
is raised.
對象的狀态存在,則傳回狀态值,若不存在,則傳回AttributeError:資訊
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name, score):
self.name = name
self.score = score
def run(self):
print 'Animal is run'
class Dog(Animal):
def run(self):
print 'Dog is run'
dog = Dog('Pity', 98)
dog.run()
print getattr(dog, 'name')
print getattr(dog, 'run')
print getattr(dog, 'd')
2.hasattr()
-
(object, name)¶hasattr
- The arguments are an object and a string. The result is
if the string is the name of one of the object’s attributes,True
if not. (This is implemented by callingFalse
getattr(object,
name)
and seeing whether it raises an exception or not.)
參數是對象和字元串,如果字元串是對象中的,傳回True,否則傳回False
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name, score):
self.name = name
self.score = score
def run(self):
print 'Animal is run'
class Dog(Animal):
def run(self):
print 'Dog is run'
dog = Dog('Pity', 98)
print hasattr(dog, 'color')
3.setattr()
-
(object, name, value)¶setattr
- This is the counterpart of
. The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example,getattr()
setattr(x,
'foobar',
is equivalent to123)
x.foobar
=
123
.
設定屬性變量
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name, score):
self.name = name
self.score = score
def run(self):
print 'Animal is run'
class Dog(Animal):
def run(self):
print 'Dog is run'
dog = Dog('Pity', 98)
setattr(dog, 'color', '0xff00ff')
print dog.color