类与类之间的关系

依赖关系:

class Elephant:

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

    def open(self, ref): # 想要的是一个冰箱。 是哪个冰箱没有制定
        print("冰箱哥哥, 开门把")
        ref.open_door()

    def close(self, ref): # 依赖关系
        print("冰箱哥哥, 我进来了。 关门把")
        ref.close_door()

    def jin(self):
        print("进冰箱装自己")

class Refrigerator:

    def open_door(self):
        print("冰箱陌陌的打开了自己的门")
    def close_door(self):
        print("冰箱陌陌的关上了自己的门 ")

alex = Elephant("李杰")
bx1 = Refrigerator()

alex.open(bx1)
alex.jin()
alex.close(bx1)  

关联关系

class Boy(object):
    def __init__(self,name,nvpengyou=None):
        self.name = name
        self.nvpengyou = nvpengyou
    def yujian(self,nv):
        self.nvpengyou = nv
    def chi(self):
        if self.nvpengyou:
            print('随便吃!%s和%s'%(self.name,self.nvpengyou.name))
        else:
            print('单身狗,吃什么饭')
class Girl:
    def __init__(self,name):
        self.name = name

alex = Boy('金角')
obj = Girl('女')

alex.yujian(obj)
alex.chi()

  

特殊成员:

class Foo:
    def __init__(self):
        print('初始化')
#类名() __init__()构造方法
obj = Foo()

 call   靠

class Foo:
    def __call__(self, *args, **kwargs):
        print('我是靠')
obj = Foo()
#对象() __call__()调用对象自动执行靠方法
obj()

 getitem  盖特唉特木

class Foo:
    def __getitem__(self, item):
        print('我是getitem',item)
        return '哈哈'
obj = Foo()
#对象[xxx] 从对象中获取数据,默认执行 __getitem__(self, item):
print(obj['杰大大'])

 setitem  赛特爱特木

class Foo:
    def __setitem__(self, key, value):
        print(key,value)
obj = Foo()
obj['汪峰'] = '章子怡'

 delitem  

class Foo:
    def __delitem__(self, key):
        print(key)
obj = Foo()#删除字典
del obj['麻花藤']

  add

class Foo:
    def __init__(self,a):
        self.a = a
    def __add__(self, other):
        return self.a + other.a
obj = Foo(1)
obj1 = Foo(555)
s = obj+obj1
print(s)

  

enter   恩特     exit   艾克c特

class Foo:
    def __enter__(self):
        print('进入')
        return '周润发'
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('出来')
obj = Foo()
with obj as xx:
    print(xx)
    print('你好我叫杰')

 hash  干掉可哈希

class Foo(object):
    __hash__ = None
obj = Foo()

  

str

class Boy(object):
    def __init__(self,name,didian,dianhua):
        self.name = name
        self.didian = didian
        self.dianhua = dianhua
    def __str__(self):
        return '%s,%s,%s'%(self.name,self.didian,self.dianhua)
obj= Boy('alex','沙河','10086')
print(obj)

  

new   牛

class Boy(object):
    def __new__(cls, *args, **kwargs):
        print('先跑new,的结果在给init,init才有结果')
        return object.__new__(cls)#才是创建对象开辟内存
obj = Boy()

  

object   奥布zhA特

 

posted @ 2018-10-07 15:29  咖啡·  阅读(404)  评论(0编辑  收藏  举报