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

0 投票
1 回答
18669 浏览
提问于 2025-04-28 05:00

我刚开始学Python,想要创建一个类,这个类里面可以使用另一个对象的功能,但我不知道该怎么做。希望能得到一些帮助,谢谢!!

这是我想做的一个大概例子:

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

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

 def bark2(self):
  ???

我想在DogHouse这个类里调用狗的叫声功能,但我不太确定该怎么正确地做到这一点。

暂无标签

1 个回答

2

你说的其实是面向对象编程。我建议你去大学上个相关课程,或者在网上学习。不过我花了一点时间给你准备了一个简单的例子,帮助你理解你想要的内容:

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的实例化方法,就会看到这两种情况是怎么演示的。

撰写回答