【问题标题】:Why doesn't this constructor allow this function to print hello world?为什么这个构造函数不允许这个函数打印 hello world?
【发布时间】:2020-10-10 10:11:01
【问题描述】:

我正在尝试了解 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

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

【问题讨论】:

  • 在这两个示例中,您都没有调用方法t.greeting()。首先,您需要通过类 (test.hello) 或实例 (self.hello) 访问类属性。我建议阅读例如docs.python.org/3/tutorial/classes.html.
  • 谢谢,帮助很大,但是我什么时候知道什么时候自己调用不带括号的方法,什么时候调用带括号的方法?
  • 不能调用没有括号的方法。没有括号,您只是访问属性,而不是调用值。
  • 这很有意义,谢谢。

标签: python class object printing constructor


【解决方案1】:

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()

【讨论】:

    【解决方案2】:

    你需要打电话打招呼,像这样t.greeting()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 2012-02-10
      • 2022-11-26
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多