天天看点

学习笔记:python的类

__init__的用法

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        # ***self*** in python is similar with ***this*** in c++. It is a pointer of instance of the objectin in class
        # the __init__() method is called the constructor and is always called when an object is created.
        # Constructors are generally used for instantiating an object.
        self.name = n
        self.age = a
        self.__weight = w   # to define a private member, prefix __ to member name 
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
# 实例化类
p = people('runoob',10,30)
p.speak()