python - 为什么这个构造函数不允许这个函数打印 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
我要做的就是创建一个包含一个变量的类,然后用那个确切的类中的函数打印该变量,我做错了什么?
解决方案
你需要打电话问候,像这样t.greeting()
。
对于您的第一次 pyhton 尝试,当您访问类变量时,您可能需要这样做print(test.hello)
推荐阅读
- c# - 将 GUI.Label 绘制到鼠标位置
- elasticsearch - 在 Kibana /Elastic Search 中聚合嵌套字段
- angular - angular,fb 仪表板(留言板),如何在组件模板中设置 url
- terraform - 如何使用 Terraform 从 AWS EMR 中分离/删除 EBS 卷?
- python - 训练步骤中的标签错误:InvalidArgumentError:断言失败:[标签 ID 必须 >= 0]
- php - 将 CKEditor 添加到我的 html/php 页面
- java - IBM Watson APIs Java SDK 使用 Watson 令牌认证失败
- php - 如何避免得到数量的负值?
- php - 带有 laravel 5.5.40 mongo db laravel 提供程序的 PHP 7
- sql - NoSQL 数据库如何实现比某些关系数据库更好的写入吞吐量?