首页 > 解决方案 > 为什么这个构造函数不允许这个函数打印 hello world?

问题描述

我正在尝试了解 python 类和对象,但与 Java 等其他编程语言相比,我很难学习对象和类在 python 中的工作方式。例如,在这个简单的 Java 代码中,我设法hello world通过创建 Class 的对象Hello并调用名为greeting

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

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

标签: pythonclassobjectprintingconstructor

解决方案


你需要打电话问候,像这样t.greeting()

对于您的第一次 pyhton 尝试,当您访问类变量时,您可能需要这样做print(test.hello)


推荐阅读