python类之间调用

来源:互联网 发布:淘宝关键词指数查询 编辑:程序博客网 时间:2024/06/03 03:25

方法1

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()

 

 

方法2
 

Python不用向C++那样考虑问题。如果你的这部分应用真的speed critical的话,用C++重写函数,打包后用Python调用,这本来就是Python的一个特点么。

我在举个做属性的例子,这些东西只要传递了,就不用担心实例化的问题,除非本身就是新生成的.

 

class A(object):             

    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的实例,

        # 如果AB中被实例化了的话

        temp = inData

        print(temp)

        #return temp  #如果需要的话,这样可以将A的实例一直传下去,Python会自动管理内存(指针)

      

# 应用实例

a = A()

b = B(a)          # A的实例传给B的属性

c = C()

  

c.method(b.attri) # 通过B的属性调用到了A的实例