Python 面向对象编程练习

标签 python

我正在尝试学习使用Python中的类,并编写了这个测试程序。 它在某种程度上基于我在另一个问题中找到的代码 堆栈溢出。

代码如下:

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major
    def list_values():
        print "Name: ", self.name
        print "Age: ", self.age
        print "Major: ", self.major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

print "A list of students."
Steve = make_student("Steven Schultz",23,"English")
Johnny = make_student("Jonathan Rosenberg",24,"Biology")
Penny = make_student("Penelope Meramveliotakis",21,"Physics")
Steve.list_values()
Johnny.list_values()
Penny.list_values()

当我运行此命令时,收到错误“TypeError:list_values() 不带参数(给定 1 个)”。 在我看来,我没有给出任何论据,但我删除了括号,给出了 代码

Steve.list_values
Johnny.list_values
Penny.list_values

这不会出现任何错误,但不会执行任何操作 - 不会打印任何内容。

我的问题:

  1. 括号有什么用?
  2. 打印语句有什么用?

最佳答案

list_values 方法需要绑定(bind)到您的 Student 实例:

你应该改变:

def list_values()

至:

def list_values(self)

有关原因的解释,请参阅:

Guido 的这篇博文也涵盖了这个主题:

关于Python 面向对象编程练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23214027/

相关文章:

python - 在 python 中过滤生成的排列

python - 如何检查 iPython 中对象的内存使用情况?

python - 使用没有 IPyWidgets 的拥抱脸转换器

python - 关联对象处理、将子项附加到父项、隐藏 “middle” 表的使用

python - 将 n 个 3x3 旋转矩阵的数组与 3 个向量的 3d 数组相乘

Python serial.readline() 不阻塞

python - 如何使用 pd.Timestamp 函数将数据列更改为时间戳格式

python - 定义列表时有条件地将项目添加到列表中?

python - 将 python 与 c/fortran 进行比较

python - 我想使用 csv 文件中的行附加文本文件