Python语言学习 (四)1.1

经典类,新式类

经典类是指没有继承的,新式类是继承了的。现在基本是新式类。

#encoding=utf-8

#经典类
class Dog:
pass

#继承了object,为新式类
class DogNew(object):
pass

#可输出此类是什么类型的类
print type(Dog)
print type(DogNew)


class Heibei(Dog):
pass

class Bomei(DogNew):
pass

print type(Heibei)
print type(Bomei)

结果:

<type 'classobj'>
<type 'type'>
<type 'classobj'>
<type 'type'>

 

方法:是对类行为的封装

实例方法:self关键字,通过self访问实例属性,调用实例方法

特殊方法:编译器自动添加的方法,self关键字(比如init)

静态方法:@staticmethod (装饰器)

类方法:@classmethod(装饰器)

 

属性的可见性:

共有属性:在类中和类外使用的属性

内置属性:编译器自动添加的属性,比如__dict__

私有属性:只能在类内使用的属性,__,会被改名换姓,_,不会被改名,象征意义大于实际意义。

#encoding=utf-8
class Person(object):
pass

class Chinese(Person):
#定义类属性
nation = 'China'

def __init__(self, name, age, sex):
#定义实例属性
self.name = name
self._age = age
self.__sex = sex

zhangsan = Chinese('zhangsan', 18, 'male')
print zhangsan.name
print zhangsan._age
print zhangsan._Chinese__sex
#print zhangsan.__sex
print dir(Chinese)

结果:

zhangsan
18
male
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'nation']

 

posted @ 2016-08-10 00:38  TinaGao  阅读(262)  评论(0编辑  收藏  举报