码迷,mamicode.com
首页 > 编程语言 > 详细

python 对象的初始状态(构造函数)

时间:2020-02-10 12:12:17      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:调用   属性   foo   添加   imei   默认   自动调用   class   创建   

class Person(object):
#name = "stu"
#age = 10
#height = 160
#weight = 90
def run(self):
print("run")
def eat(self, food):
print("eat " + food)

def __init__(self, name, age, height, weight):
#print(name, age, height, weight)
#定义属性
self.name = name
self.age = age
self.height = height
self.weight = weight

‘‘‘
构造函数:__init__() 在使用类创建对象的时候自动调用
注意:如果不显示的写出构造函数,默认会自动添加一个空的构造函数
‘‘‘
per = Person("hanmeimei", 20, 170, 55)
print(per.name, per.age)

per2 = Person("lilei", 21, 175, 70)
print(per2.name, per2.age)

per.run()

python 对象的初始状态(构造函数)

标签:调用   属性   foo   添加   imei   默认   自动调用   class   创建   

原文地址:https://www.cnblogs.com/pygo/p/12290220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!