以下是 Python 代码示例,展示了 Person 类的定义和对象实例化,以及最终的运行结果:

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def say_hello(self):
        print('Hello, my name is', self.name, 'and I am', self.age, 'years old.')

    if __name__ == '__main__':
        per = Person('wangmei', 19)
        per.say_hello()

程序运行结果是:

Hello, my name is wangmei and I am 19 years old.

这段代码定义了一个名为 Person 的类,它包含两个方法:

  • __init__: 初始化方法,用于创建 Person 对象时设置姓名和年龄属性。
  • say_hello: 用于打印问候语,包含姓名和年龄信息。

if __name__ == '__main__' 代码块中,我们创建了一个名为 per 的 Person 对象,并调用了其 say_hello 方法,最终输出问候语。


原文地址: https://www.cveoy.top/t/topic/nZBi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录