你在说什么是object oriented programming。我建议你在大学或online上选修一门课程。不过,我已经采取了时间掀起一个简单的例子做什么,我觉得你想要它做的:
class A(object):
def __init__(self):
print("hello world")
def new_print(self, some_word):
print(some_word.swapcase())
@staticmethod
def newer_print(some_word):
print(some_word.lower())
class B(object):
def __init__(self):
print("world")
#create the object of Class A and then call the method
temp = A()
temp.new_print("This is a test")
#call the static method of Class A
A.newer_print("Just one more test")
if __name__ == "__main__":
#create the object for Class B
test = B()
注意Class A
有两个方法(除了__init__
)。第一个(new_print
)要求在调用方法之前实例化该类的一个对象。第二个(newer_print
)可以静态运行。
调用另一个类的方法是简单地完成或者:
- 创建类的一个对象,并调用它的方法,或者
- 调用类的静态方法
如果你看看在B的实例化方法中,你会看到这两种情况都被证明了。
粘贴我们你的代码(格式为Ctrl-K),找出具体的问题,然后我们可以批评它。 – smci 2014-10-17 22:12:03
*“我试图创建一个使用另一个对象的函数的类”*你的意思是B类使用A的方法,但B不是A的子类? B中的方法可以调用A实例的方法,但只有一个深度的调用级别......不违反Demeter法则*(“对象引用中最多一个点”)* – smci 2014-10-17 22:14:51
...或否则,如果你想让A和B两个类共享一些方法,那么让它们都从一个公共基类C继承。你可以强制该方法是抽象的/没有一个默认的实现,通过'raise Exception'。没有看到具体细节和代码,很难知道你真正想要什么。 – smci 2014-10-17 22:16:39