Python 类和对象:Person 类示例运行结果
下面程序定义了一个名为 'Person' 的类,包含 'name' 和 'age' 属性,以及 'say_hello' 方法,用于打印对象的姓名和年龄。
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' 对象 'per',并传入参数 'wangmei' 和 19 分别初始化 'name' 和 'age' 属性。然后调用 'per' 对象的 'say_hello' 方法,打印了对象的姓名和年龄信息。
原文地址: https://www.cveoy.top/t/topic/nZGk 著作权归作者所有。请勿转载和采集!