一、 类和对象的概念 对象=属性+行为(方法)
把具有相同属性和方法的对象归为一类。 类是对象的抽象化,对象是类的实例化。 二、 类的定义、实例化、属性和方法的调用 class 类名: 属性
方法 >>> class people: name='jim' age=20
def printName(self):
print self.name
>>> people.name 'jim' >>> people.p
Traceback (most recent call last): File \ people.p
AttributeError: class people has no attribute 'p' >>> people.printName()
Traceback (most recent call last): File \ people.printName()
TypeError: unbound method printName() must be called with people instance as first argument (got nothing instead) >>> people.printName(self)
Traceback (most recent call last): File \ people.printName(self)
NameError: name 'self' is not defined >>> p=people() >>> p.name 'jim' >>> p.age 20
>>> p.printName() jim
>>> class people1:
__name='mike' __age=20 sex='wemom'
>>> p1=people1() >>> p1.__name
Traceback (most recent call last):
File \ p1.__name
AttributeError: people1 instance has no attribute '__name' >>> p1.__age
Traceback (most recent call last):
File \ p1.__age
AttributeError: people1 instance has no attribute '__age' >>> p1.sex 'wemom' >>> p1.sex 'wemom'
类的内置函数 class c1: def tell(self):
print \
def __init__(self):
print \
def __del__(self):
print \
>>> c11=c1() c1 is init >>> >>> c11=0 c1 is del
三、 类属性、实例属性、类方法、实例方法、静态方法>>> class people: name='alice' __age=13
>>> p=people() >>> p.name 'alice' >>> p.__age
Traceback (most recent call last):
File \ p.__age
AttributeError: people instance has no attribute '__age' 实例对象可以调用类里面定义的公有属性,不能调用私有属性。
>>> people.name 'alice'
>>> people.__age
Traceback (most recent call last):
File \ people.__age
AttributeError: class people has no attribute '__age' >>>类对象可以调用类里面定义的公有属性,不能调用私有属性。
>>> p.sex='man' #sex是实例属性