Python学习总结19:类(一)

在Python中,可以通过class关键字定义自己的类,通过类私有方法“__init__”进行初始化。可以通过自定义的类对象类创建实例对象

class Student(object):
    count = 0
    books = []
    def __init__(self, name, age):
        self.name = name
        self.age = age
    pass

1. 数据属性

在上面的Student类中,”count””books””name”和”age”都被称为类的数据属性,但是它们又分为类数据属性实例数据属性

Student.books.extend(["python", "javascript"])
print "Student book list: %s" %Student.books
# class can add class attribute after class defination
Student.hobbies = ["reading", "jogging", "swimming"]
print "Student hobby list: %s" %Student.hobbies
print dir(Student)

wilber = Student("Wilber", 28)
print "%s is %d years old" %(wilber.name, wilber.age)
# class instance can add new attribute
# "gender" is the instance attribute only belongs to wilber
wilber.gender = "male"
print "%s is %s" %(wilber.name, wilber.gender)
# class instance can access class attribute
print dir(wilber)
wilber.books.append("C#")
print wilber.books

will = Student("Will", 27)
print "%s is %d years old" %(will.name, will.age)
# will shares the same class attribute with wilber
# will don‘t have the "gender" attribute that belongs to wilber
print dir(will)
print will.books

通过内建函数dir(),或者访问类的字典属性__dict__,这两种方式都可以查看类有哪些属性。

>>> print dir(Student)
[‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__module__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘books‘, ‘count‘, ‘hobbies‘]

    1)特殊的类属性

     对于所有的类,都有一组特殊的属性:

类属性 含义
__name__ 类的名字(字符串)
__doc__ 类的文档字符串
__bases__ 类的所有父类组成的元组
__dict__ 类的属性组成的字典
__module__ 类所属的模块
__class__ 类对象的类型

     2)属性隐藏

类数据属性属于类本身,被所有该类的实例共享;并且,通过实例可以去访问/修改类属性。但是,在通过实例中访问类属性的时候一定要谨慎,因为可能出现属性”隐藏”的情况。

wilber = Student("Wilber", 28)

print "Student.count is wilber.count: ", Student.count is wilber.count
wilber.count = 1
print "Student.count is wilber.count: ", Student.count is wilber.count
print Student.__dict__
print wilber.__dict__
del wilber.count
print "Student.count is wilber.count: ", Student.count is wilber.count

print 

wilber.count += 3
print "Student.count is wilber.count: ", Student.count is wilber.count
print Student.__dict__
print wilber.__dict__

del wilber.count
print

print "Student.books is wilber.books: ", Student.books is wilber.books
wilber.books = ["C#", "Python"]
print "Student.books is wilber.books: ", Student.books is wilber.books
print Student.__dict__
print wilber.__dict__
del wilber.books
print "Student.books is wilber.books: ", Student.books is wilber.books

print 

wilber.books.append("CSS")
print "Student.books is wilber.books: ", Student.books is wilber.books
print Student.__dict__
print wilber.__dict__

2. 方法

    在一个类中,可能出现三种方法,实例方法、静态方法和类方法。

1)实例方法

实例方法的第一个参数必须是”self”,”self”类似于C++中的”this”。

实例方法只能通过类实例进行调用,这时候”self”就代表这个类实例本身。通过”self”可以直接访问实例的属性。

class Student(object):
    ‘‘‘
    this is a Student class
    ‘‘‘
    count = 0
    books = []
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def printInstanceInfo(self):
        print "%s is %d years old" %(self.name, self.age)
    pass

wilber = Student("Wilber", 28)
wilber.printInstanceInfo()

2)类方法
    类方法以cls作为第一个参数,cls表示类本身,定义时使用@classmethod装饰器。通过cls可以访问类的相关属性。

class Student(object):
    ‘‘‘
    this is a Student class
    ‘‘‘
    count = 0
    books = []
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def printClassInfo(cls):
        print cls.__name__
        print dir(cls)
    pass

Student.printClassInfo()
wilber = Student("Wilber", 28)
wilber.printClassInfo()

3)静态方法

 与实例方法和类方法不同,静态方法没有参数限制,既不需要实例参数,也不需要类参数,定义的时候使用@staticmethod装饰器。 同类方法一样,静态法可以通过类名访问,也可以通过实例访问。
class Student(object):
    ‘‘‘
    this is a Student class
    ‘‘‘
    count = 0
    books = []
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def printClassAttr():
        print Student.count
        print Student.books
    pass

Student.printClassAttr()
wilber = Student("Wilber", 28)
wilber.printClassAttr()

这三种方法的主要区别在于参数,实例方法被绑定到一个实例,只能通过实例进行调用;但是对于静态方法和类方法,可以通过类名和实例两种方式进行调用。

3. 访问控制

     在Python中,通过单下划线”_”来实现模块级别的私有化,一般约定以单下划线”_”开头的变量、函数为模块私有的,也就是说”from moduleName import *”将不会引入以单下划线”_”开头的变量、函数。

现在有一个模块lib.py,内容用如下,模块中一个变量名和一个函数名分别以”_”开头:

numA = 10
_numA = 100

def printNum():
    print "numA is:", numA
    print "_numA is:", _numA

def _printNum():
    print "numA is:", numA
print "_numA is:", _numA

当通过下面代码引入lib.py这个模块后,所有的以”_”开头的变量和函数都没有被引入,如果访问将会抛出异常:

from lib import *
print numA
printNum()

print _numA
#print _printNum()

     双下划线”__”

对于Python中的类属性,可以通过双下划线”__”来实现一定程度的私有化,因为双下划线开头的属性在运行时会被”混淆”(mangling)。

在Student类中,加入了一个”__address”属性:

class Student(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.__address = "Shanghai"
    pass

wilber = Student("Wilber", 28)
print wilber.__address

当通过实例wilber访问这个属性的时候,就会得到一个异常,提示属性”__address”不存在。

其实,通过内建函数dir()就可以看到其中的一些原由,”__address”属性在运行时,属性名被改为了”_Student__address”(属性名前增加了单下划线和类名)

>>> wilber = Student("Wilber", 28)
>>> dir(wilber)
[‘_Student__address‘, ‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__form
at__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__module__‘, ‘__new__‘, ‘__r
educe__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘
__subclasshook__‘, ‘__weakref__‘, ‘age‘, ‘name‘]

所以说,即使是双下划线,也没有实现属性的私有化,因为通过下面的方式还是可以直接访问”__address”属性:

>>> wilber = Student("Wilber", 28)
>>> print wilber._Student__address
Shanghai

双下划线的另一个重要的目地是,避免子类对父类同名属性的冲突。

class A(object):
    def __init__(self):
        self.__private()
        self.public()

    def __private(self):
        print ‘A.__private()‘

    def public(self):
        print ‘A.public()‘

class B(A):
    def __private(self):
        print ‘B.__private()‘

    def public(self):
        print ‘B.public()‘

b = B()

当实例化B的时候,由于没有定义__init__函数,将调用父类的__init__,但是由于双下划线的”混淆”效果,”self.__private()”将变成 “self._A__private()”

“_”和” __”的使用 更多的是一种规范/约定,不没有真正达到限制的目的:

“_”:以单下划线开头的表示的是protected类型的变量,即只能允许其本身与子类进行访问;同时表示弱内部变量标示,如,当使用”from moduleNmae import *”时,不会将以一个下划线开头的对象引入。
     “__”:双下划线的表示的是私有类型的变量。只能是允许这个类本身进行访问了,连子类也不可以,这类属性在运行时属性名会加上单下划线和类名。

总结

本文介绍了Python中class的一些基本点:

  • 实例数据属性和类数据属性的区别,以及属性隐藏
  • 实例方法,类方法和静态方法直接的区别
  • Python中通过”_”和”__”实现的访问控制
时间: 2024-08-07 21:19:30

Python学习总结19:类(一)的相关文章

Python学习心得:类与对象

教材:<简明Python教程> Python面向对象: 如shell这种面向过程的程序都是通过"操作数据的函数"或者"语句块"来设计函数. python的程序(面向对象): 类是一个"class"类型,对象是类中的一个实例. 类的属性包括了:域和方法.(即变量和函数) 属于一个对象或类的变量被称为域,一个定义在类中的函数,叫做类的方法. 类使用关键字"class"来创建.域和方法放在同一个缩进块中. 1.域有两种:

Python学习之定制类

本文和大家分享的主要是 python开发中定制类的相关内容,一起来看看吧,希望对大家学习和使用这部分内容有所帮助. 1. python中什么是特殊方法 任何数据类型的实例都有一个特殊方法:  __str__() ·  用于 print 的  __str__ ·  用于 len 的  __len__ ·  用于 cmp 的  __cmp__ ·  特殊方法定义在 class 中 ·  不需要直接调用 · Python 的某些函数或操作符会调用对应的特殊方法 file:///C:\Users\wlc

Python学习—常用时间类与命名元组

常用时间类与命名元组 1. 常用时间类date 日期类time 时间类datetimetimedelat 时间间隔2. 一些术语和约定的解释:1.时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日开始按秒计算的偏移量(time.gmtime(0))此模块中的函数无法处理1970纪元年以前的时间或太遥远的未来(处理极限取决于C函数库,对于32位系统而言,是2038年)2.UTC(Coordinated Universal Time,世界协调时)也叫格林威治天文时间,是

python学习笔记1-元类__metaclass__

type 其实就是元类,type 是python 背后创建所有对象的元类 python 中的类的创建规则: 假设创建Foo 这个类 class Foo(Bar): def __init__(): pass Foo中有__metaclass__这个属性吗?如果有,Python会在内存中通过__metaclass__创建一个名字为Foo的类对象,他是一个类,但是本身类就是对象,一个python文件模块也属于一个对象. 如果Python没有找到__metaclass__,它会继续在Bar(父类)中寻找

Python学习笔记008_类_对象

# 对象 = 属性 + 方法>>> # Python中的类名约定以大写字母开始>>> # tt = Turtle() 这就是创建类实例的方法,其它语言用new ,它是不需要的>>> >>> # Python中的self就相当于Java中的this >>> # self ,一般都放在方法的第一个参数中这是默认的要求 class Ball: def setName(self,name): self.name=name d

Python学习笔记12—类

典型的类和调用方法: #!/usr/bin/env Python # coding=utf-8 __metaclass__ = type #新式类 class Person: #创建类 def __init__(self, name): #初始化函数 self.name = name def getName(self): #类中的方法(函数) return self.name def color(self, color): print "%s is %s" % (self.name,

python学习笔记——旧类与新类继承中的构造函数

旧类以调用未绑定的超类构造方法 class OldDog: def __init__(self): print 'I am a old dog !' self.__hungry = True def eat(self): if self.__hungry: print 'I eat it !' self.__hungry = False else: print 'No thanks!' class OldWolf(OldDog): def __init__(self): OldDog.__ini

python学习——使用元类

type() 动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的. 比方说我们要定义一个Hello的class,就写一个hello.py模块: class Hello(object): def hello(self, name='world'): print('Hello, %s.' % name) 当Python解释器载入hello模块时,就会依次执行该模块的所有语句,执行结果就是动态创建出一个Hello的class对象,测试如下: >>> fro

python学习笔记(七) 类和pygame实现打飞机游戏

python中类声明如下: class Student(object): def __init__(self, name, score): self.name = name self.score = score def printinfo(self): print('name is %s, score is %d'%(self.name, self.score)) Student类有两个成员变量,name和score,类的成员函数第一个参数都为self,用来实现成员变量的赋值,__init__是