python学习日记(7)

  • 类的私有变量
    • 定义
    • 继承
    • 私有变量
  • 鸭子类型
  • 判断数据类型
    • type
    • isinstance
    • dir
      • getattrsetattr以及hasattr

类的私有变量

定义

#class的定义
class example:
    def __init__(self, name):
        example.name = name

#或者
class example(object):
    def __init__(self, name):
        example.name = name

继承

class son(father):
    def __init__(self, name):
        example.name = name

私有变量

class example:
    def __init__(self, name):
        example.__name = name
#__name就是私有

鸭子类型

python的继承是多态的,但是却不是严格多态的

class father(object):
    def run(self):
        print("father")

class son(father):
    pass

class other(object):
    def run(self):
        print("other")

def run2(father):
    father.run()
    father.run()
  • run2虽然是传入father的,但是传入other也无所谓。所谓other看起来像father,所以它就可以看作是father拿来用

run2(father())
run2(son())
run2(other())
#皆可

判断数据类型

type

type("abc") == str

isinstance()

isinstance("abc", str)

dir()

#一次性获得所有属性和方法
dir(father())
#或者
dir(father)

getattr()、setattr()以及hasattr()

获得,设置,是否存在某个属性attr

hasattr(father, "run")
setattr(father, "__document__", "test")
getattr(father, "__document__")

你可能感兴趣的:(我的学习日记,python)