Python:如何将一个对象传递到另一个类的参数中?

2024-05-23 14:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。我试图创建一个类,在其中使用另一个对象的函数,但我不确定如何做到这一点。如有任何帮助,我们将不胜感激。谢谢您!!

所以这是我想做的一个粗略的例子

class Dog:
	def bark(self):
		print("Hello")

class DogHouse:
	def __init__(self, dog):
		self.owner = dog

	def bark2(self):
		???

所以我想在狗屋里叫出狗的叫声,但我不确定如何正确地叫出。


Tags: 对象函数selfhelloinitdefclass例子
1条回答
网友
1楼 · 发布于 2024-05-23 14:33:34

你说的是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)可以静态运行。

调用另一个类方法只需执行以下操作之一:

  1. 创建类的对象并调用其方法,或者
  2. 调用类的静态方法

如果你看看B的实例化方法,你会发现这两个例子已经演示过了。

相关问题 更多 >