我试图了解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
我所要做的就是创建一个包含变量的类,然后将该变量与该类中的函数一起打印,我做错了什么?
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()
。
对于您的第一次pyhton尝试,当您访问类变量时,您可能需要这样做print(test.hello)