python构造函数

#   面向对象
#   有意义的面向对象的代码
#   类 = 面向对象
#   实例化
#   类的最基本的作用:封装代码
#   类和对象    类就像是一个模板,可以产生很多对象
class Student():
    name = ''
    age = 0
    def __init__(self):
        #   它是构造函数
        print('student')
    #行为     与   特征
    def do_homework(self):
        print('homework')



 #  调用类下面的函数
student1 = Student()
student2 = Student()
student3 = Student()
# print(id(student1))
# print(id(student2))
# print(id(student3))

会打印出三个不同的id

class Student():
    name = ''
    age = 0
    def __init__(self):
        #   它是构造函数
        print('student')
    #行为     与   特征
    def do_homework(self):
        print('homework')

student1 = Student()
student1.__init__()

会打印出来两个student

p s : 1. 构造函数的调用是自动进行的。当你实例化的时候,python会自动调用__init__()。

         2.我们可以主动的去调用__init__()。

如果我们显式调用构造函数,它其实跟普通的函数没有什么区别。python默认函数返回的是None。

构造函数的作用:可以让模板生成不同的对象

如果我们尝试去访问一个实例对象,python首先会在实例对象列表里面查找到底有没有这样一个变量。如果没有的话,会继续到类变量列表里面寻找。

猜你喜欢

转载自blog.csdn.net/ferrysoul/article/details/82829449
今日推荐