classes
(1)使用isinstance函数 来判断一个对象的类型
isinstance(object, class-or-object-or-tuple)
第二个参数不能为object。可以是type的tuple
这个函数在很多地方应该用到,很多新手和我一样没用在正确地方吧。
def get_size(some_object):
"""Return the "size" of *some_object*, where size = len(some_object) for
sequences, size = some_object for integers and floats, and size = 1 for
True, False, or None."""
try:
return len(some_object)
except TypeError:
if some_object in (True, False, type(None)):
return 1
else:
return int(some_object)
print(get_size('hello'))
print(get_size([1, 2, 3, 4, 5]))
print(get_size(10.0))
每当这时候想到过用isinstance
def get_size(some_object):
if isinstance(some_object, (list, dict, str, tuple)):
return len(some_object)
elif isinstance(some_object, (bool, type(None))):
return 1
elif isinstance(some_object, (int, float)):
return int(some_object)
print(get_size('hello'))
print(get_size([1, 2, 3, 4, 5]))
print(get_size(10.0))
(2)private
不太能说得清开得不是太深,先保留
如果要将一个方法声明为private的,只要在方法名前面加上__
def
__private_method
(self):
由此可以知道所以的如__repr__, __init__, __add__都是不能直接调用的.
这些私有方法的名字在外部是不可见的,只有在内部才可以调用,由于加上了__来区分名字,所以我们可以再定义一个没有__的共有同名方法。
_xxx 单下划线开头,类似于php中的protected,意思是受保护的,只能再本类以及子类中访问
__xxx 双下划线,类似于private,私有的,只能本类中访问,连子类都无法访问
(3)使用属性
有几个特殊的类属性
__name__ __doc__ __bases__ __dict__ __module__ __class__
(4)__repr__的使用
对应repr(object)这个函数,返回一个可以用来表示对象的可打印字符串
用来给机器输出的,例如:
log_to_console([Foo(), Foo(cache={'x': 'y'})])
找了个例子来说明__repr__和__str__的作用
>>> class D(object):
... def __str__(self):
... return "a __str__"
... def __repr__(self):
... return "a __repr__"
...
>>> dr = D()
>>> print dr
a __str__
>>> dr
a __repr__
>>> "%s" % dr
'a __str__'
>>> "%r" % dr
'a __repr__'
(5)__str__的使用
用来增加可读性:
# Harmful
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p)
# Prints '<__main__.Point object at 0x91ebd0>'
# Idiomatic
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '{0}, {1}'.format(self.x, self.y)
p = Point(1, 2)
print(p)
# Prints '1, 2'