Python 为什么';此构造函数是否允许此函数打印hello world?

Python 为什么';此构造函数是否允许此函数打印hello world?,python,class,object,printing,constructor,Python,Class,Object,Printing,Constructor,我试图学习python类和对象,但与Java等其他编程语言相比,在学习python中的对象和类如何工作时遇到了困难。例如,在这个简单的Java代码中,我通过创建类hello的对象并调用名为greeting的方法来打印hello world public class HelloWorld{ public static void main(String []args){ Hello test = new Hello(); test.greeting(); } }

我试图学习python类和对象,但与Java等其他编程语言相比,在学习python中的对象和类如何工作时遇到了困难。例如,在这个简单的Java代码中,我通过创建类
hello
的对象并调用名为
greeting
的方法来打印
hello world

public class HelloWorld{

 public static void main(String []args){
    Hello test = new Hello();
    test.greeting();
    
   }
}
class Hello{
    String hello = "hello world";

    public void greeting(){
        System.out.println(hello);
  }
}
然而,当我尝试在python中执行同样的操作时,它似乎不会打印任何内容

class test:
    hello = "hello world"

    def greeting():
        print(hello)

t = test()
t.greeting
我甚至尝试使用构造函数,但仍然没有打印出来

class test:
    def __init__(self):
        self.hello = "hello world"

    def greeting(self):
        print(self.hello)

t = test()
t.greeting

我所要做的就是创建一个包含变量的类,然后使用该类中的函数打印该变量,我做错了什么?

您需要调用greeting,就像这样
t.greeting()


对于您的第一次Pyton尝试,当您访问类变量时,您可能需要这样做:print(test.hello)
hello
是一个类属性。可以使用
classname.classattribute
访问它们,因此在本例中:
Test.hello

class Test:
    hello = "Hello world"

    def greeting(self):
         print(Test.hello)
在python中,函数也是对象:
t.greeting
是方法
t.greeting()
调用该方法

t = Test()
t.greeting()

在这两个示例中,您都不调用方法,
t.greeting()
。首先,您需要通过类(
test.hello
)或实例(
self.hello
)访问class属性。我建议阅读,例如…,谢谢,这很有帮助,但是我什么时候知道什么时候不用括号单独调用一个方法,什么时候用括号调用一个方法?你不能调用没有括号的方法。没有括号,您只是访问属性,而不是调用值。这很有意义,谢谢。