【发布时间】: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