python3(二十五) getClassInfo

"""  """
__author__ = 'shaozhiqi'

#  如何知道这个对象是什么类型,使用type()
print(type(123))  # <class 'int'>
print(type('abc'))  # <class 'str'>
print(type(None))  # <class 'NoneType'>
print(type(abs))  # <class 'builtin_function_or_method'>
print(type(123) == type(456))  # True
print(type(123) == int)  # True
print(type('abc') == str)  # True
print(type('abc') == type(123))  # False
# 判断一个对象是否是函数
import types


def fn():
    pass


print(type(fn) == types.FunctionType)  # True
print(type(abs) == types.BuiltinFunctionType)  # True

# isinstance() 判断的是一个对象是否是该类型本身,或者位于该类型的父继承链上
# 如二十四节的
# print(isinstance(dog, Animal))  # True
# 能用type()判断的基本类型也可以用isinstance()
print(isinstance('a', str))  # True
print(isinstance(123, int))  # True
print(isinstance(b'a', bytes))  # True
# isinstance可以判断一个变量是否是某些类型中的一种
print(isinstance([1, 2, 3], (list, tuple)))

# dir()--------------------------------------------------------
# 获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list
print(dir('ABC'))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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', 'isascii', '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__()方法
print(len('ABC'))  # 3
print('ABC'.__len__())  # 3


# 也可以在我们自己的写的类中定义__len__
class MyDog(object):

    def __init__(self):
        self.nameDog = 'dog'

    def __len__(self):
        return 100

    def run(self):
        print('running  .......')


dog = MyDog()
print(len(dog))  # 100    删除__len__方法 报错
print('ABC'.lower())  # abc

print(hasattr(dog, 'nameDog'))  # True 有nameDog属性吗 有
print(hasattr(dog, 'color'))  # False 没有color属性

setattr(dog, 'color', '黑白')  # 设置一个属性'color'
print(hasattr(dog, 'color'))  # True
print(getattr(dog, 'color'))  # 黑白  获取属性的值 黑白
print(dog.color)  # 黑白
print(getattr(dog, 'age', '404'))  # 404 获取不存在的属性会报error,可设置默认值处理 404

# 获取对象的方法
print(hasattr(dog, 'run'))  # True
fn = getattr(dog, 'run')
fn()  # running  .......


# ----------实例的属性------------------------------------------------
class Student(object):
    name = 'Student'

    def __init__(self, name):
        self.name = name


s = Student('Bob')
s.score = 90
print(s.name, ',', s.score)  # Bob , 90
print(Student.name)  # Student
# 删除属性
del s.name
print(s.name, ',', s.score)  # Student , 90
Student.name = 'Student1'
print(s.name, ',', s.score)  # Student1 , 90
# 如果实例属性和类属性同名,则实例属性会覆盖掉类属性,所以实际开发中尽量避免。除非有实际业务需要这样做

猜你喜欢

转载自www.cnblogs.com/shaozhiqi/p/11550453.html