37,719
社区成员
发帖
与我相关
我的任务
分享
class A(object): # python的类一般大写
def __init__(self,attri = "总得放点什么"):
self.__attri = attri
def method(self):
print("总得做点什么")
class B(object):
def __init__(self,attri):
self.__attri = attri # 准备在应用中将A的实例传给此
def __str__(self):
rep = "class B object"
return rep
def methond(self):
print("也做点什么吧")
@property
def attri(self):
return self.__attri
class C(object):
def __init__(self):
pass
def method(self,inData):
# 准备用此方法调用B的属性,在应用中就可能捕获A的实例,
# 如果A在B中被实例化了的话
temp = inData
print(temp)
#return temp #如果需要的话,这样可以将A的实例一直传下去,Python会自动管理内存(指针)
# 应用实例
a = A()
b = B(a) # 将A的实例传给B的属性
c = C()
c.method(b.attri) # 通过B的属性调用到了A的实例
"""Jerry Cool's demo for friend."""
#!/usr/bin/env python
# -*- coding: cp936 -*-
class Me(object):
"""这就是我啦。
"""
def __init__(self,weapon = gun): # gun 可能是基本类型,也可能是一个类
self.__weapon = weapon # 私有成员变量
def fireAt(self,enemy):
"""向敌人发起攻击,敌人根据被攻击武器种类失血。
这里通过调用对方类的方法实现。我看得教材里说'看起来直接通过对方类来
调用它的方法很不礼貌,但是这要比直接调用对方类的成员变量要绅士的多'
"""
enemy.beShooted(WeaponKind = self.__weapon)
class Enemy(object):
"""这就是鬼子
"""
def __init__(self,kind):
self.__kind = kind # 通过设置property调用的私有成员变量
self.__health = 100 # 通过自己的方法调用的私有成员变量
def beShooted(self,WeaponKind):
"""失血,通过其它类调用"""
if WeaponKind == gun:
self.__health -= 10
@property # 2.6 新增
def kind(self):
"""设置成员变量为property,让它可以通过如enemy1.kind调用。不设为公用的原因
是可以控制它的access ability,如@kind.setter,@kind.deleter,而且可以附
加其它需要的操作
"""
return self.__kind
# 应用实例
me = Me()
guiZi = Enemy("boss")
print(guiZi.kind)
me.fireAt(guiZi)
class a:
def __init__(self):
self.arr1 = "i am xiaobai"
def print_out(self,x):
print x
class b:
def main(self):
mya = a()
mya.print_out(mya.arr1)
bn = b()
bn.main()
x = MyClass()
import mymod
x = mymod.MyClass()
from mymod import MyClass
x = MyClass()