python语法31[类]
一 最简单的类
python与C#一样,为纯面向对象语言,所有的类都有共同的基类object。
python的内置类型都有对应的class对应,例如整形对应的类为int,字符串对应的类为str等。
类的定义使用关键字class,类名后面()为基类的名字。
>>> class c(object): pass
>>> x = c()
>>> issubclass(c,object)
True
>>> type(10)
<class 'int'>
>>> issubclass(int,object)
True
>>> type('aaa')
<class 'str'>
>>> issubclass(str,object)
True
>>>
注意:>>> x = c()
>>> issubclass(c,object)
True
>>> type(10)
<class 'int'>
>>> issubclass(int,object)
True
>>> type('aaa')
<class 'str'>
>>> issubclass(str,object)
True
>>>
python与C#一样,为纯面向对象语言,所有的类都有共同的基类object。
python的内置类型都有对应的class对应,例如整形对应的类为int,字符串对应的类为str等。
类的定义使用关键字class,类名后面()为基类的名字。
二 简单类
>>>class MyClass:
"""This is the simple class for testing"""
i=100
def PrintI():
print(i)
def __init__(self):
self.x=10
self.y=20
self.__total=self.x+self.y
print("constructor!")
def __del__(self):
print("deconstructor!")
def __PrintTotal(self):
print(self.__total)
def PrintSelf(self):
print("print x ,y and total")
print(self.x)
print(self.y)
self.__PrintTotal()
>>> print(MyClass.__name__)
MyClass
>>> print(MyClass.__doc__)
This is the simple class for testing
>>> myC=MyClass()
constructor!
>>> myC.i
100
>>> MyClass.i
100
>>> myC.x
10
>>> myC.y
20
>>> myC.PrintSelf()
print x ,y and total
10
20
30
>>> myC._MyClass__total
30
>>> myC._MyClass__PrintTotal()
30
>>> myC.z=30
>>> myC.z
30
>>> del myC.z
>>> del myC
deconstructor!
>>>
"""This is the simple class for testing"""
i=100
def PrintI():
print(i)
def __init__(self):
self.x=10
self.y=20
self.__total=self.x+self.y
print("constructor!")
def __del__(self):
print("deconstructor!")
def __PrintTotal(self):
print(self.__total)
def PrintSelf(self):
print("print x ,y and total")
print(self.x)
print(self.y)
self.__PrintTotal()
>>> print(MyClass.__name__)
MyClass
>>> print(MyClass.__doc__)
This is the simple class for testing
>>> myC=MyClass()
constructor!
>>> myC.i
100
>>> MyClass.i
100
>>> myC.x
10
>>> myC.y
20
>>> myC.PrintSelf()
print x ,y and total
10
20
30
>>> myC._MyClass__total
30
>>> myC._MyClass__PrintTotal()
30
>>> myC.z=30
>>> myC.z
30
>>> del myC.z
>>> del myC
deconstructor!
>>>
注意:
一些默认的属性__name__表示类的名字,__doc__表示类的说明字符串,__dict__类的整个dictionary。
__init__(self)和__del__为类的默认的构造和析构函数。
myC=MyClass()用来定义实例。
i为MyClass的静态变量,可以使用MyClass.i 或myC.i来访问。
x,y为类MyClass的成员变量。
PrintSelf()为类MyClass的成员方法。
__total和__PrintTotal()为类MyClass的私有成员和方法,但是这个只是一个约定,可以使用myC._MyClass__total和myC._MyClass__PrintTotal()来访问。
z为myC的实例的成员,不属于类MyClass。
使用del来删除类对象或实例的成员变量。
三 类和对象的属性的判定和函数的修改
class Class:
answer = 42
def __init__(self):
self.x = 10
def method(self):
print( 'Hey a method')
print(hasattr(Class, 'answer'))
#True
print(hasattr(Class, 'question'))
#False
print(hasattr(Class(), 'x'))
#True
print(hasattr(Class, 'method'))
#True
print(getattr(Class, 'answer'))
#42
print(getattr(Class, 'question', 'What is six times nine?'))
#'What is six times nine?'
print(getattr(Class(), 'x'))
#10
getattr(Class(),'method')()
#'Hey a method'
class MyClass:
def method(self):
print( 'Hey a method')
instance = MyClass()
instance.method()
#'Hey a method'
def new_method(self):
print( 'New method wins!')
MyClass.method = new_method
instance.method()
#'New method wins!'
del MyClass.method
print(hasattr(MyClass, 'method'))
#False
#instance.method()
instance.y = 20
print(instance.y)
del instance.y
answer = 42
def __init__(self):
self.x = 10
def method(self):
print( 'Hey a method')
print(hasattr(Class, 'answer'))
#True
print(hasattr(Class, 'question'))
#False
print(hasattr(Class(), 'x'))
#True
print(hasattr(Class, 'method'))
#True
print(getattr(Class, 'answer'))
#42
print(getattr(Class, 'question', 'What is six times nine?'))
#'What is six times nine?'
print(getattr(Class(), 'x'))
#10
getattr(Class(),'method')()
#'Hey a method'
class MyClass:
def method(self):
print( 'Hey a method')
instance = MyClass()
instance.method()
#'Hey a method'
def new_method(self):
print( 'New method wins!')
MyClass.method = new_method
instance.method()
#'New method wins!'
del MyClass.method
print(hasattr(MyClass, 'method'))
#False
#instance.method()
instance.y = 20
print(instance.y)
del instance.y
可以使用hasattr来判断类和实例的属性是否存在,如果存在可以使用getattr来获得值,此时的属性包含变量和方法。
类和实例的属性可以在使用的过程中进行增删改,此时的属性包含变量和方法。
四 类的静态和类方法
class MyClass2:
@classmethod
def a_class_method(cls):
print ('I was called from class %s' % cls)
@staticmethod
def a_static_method():
print ('I have no idea where I was called from')
def a_static_method2():
print('i am just called by the class')
instance2 = MyClass2()
MyClass2.a_class_method()
instance2.a_class_method()
# both print 'I was called from class __main__.MyClass2'
MyClass2.a_static_method()
instance2.a_static_method()
# both print 'I have no idea where I was called from'
MyClass2.a_static_method2()
#'i am just called by the class'
#instance2.a_static_method2() # throw exception
@classmethod
def a_class_method(cls):
print ('I was called from class %s' % cls)
@staticmethod
def a_static_method():
print ('I have no idea where I was called from')
def a_static_method2():
print('i am just called by the class')
instance2 = MyClass2()
MyClass2.a_class_method()
instance2.a_class_method()
# both print 'I was called from class __main__.MyClass2'
MyClass2.a_static_method()
instance2.a_static_method()
# both print 'I have no idea where I was called from'
MyClass2.a_static_method2()
#'i am just called by the class'
#instance2.a_static_method2() # throw exception
类方法和使用staticmethod修饰的静态方法,调用方法相同,均可以使用类或对象调用。
对于没有staticmethod修饰的静态方法,只能使用类来调用。
五 类的继承
>>> class Employee:
companyname="microsoft"
def printCompany():
print(companyname)
def __init__(self,name,salary):
self.name=name
self.salary=salary
print("Constructor Employee")
def __del__(self):
print("DeConstructor Employee")
def PrintSelf(self):
print(self.name)
print(self.salary)
>>> class Developer(Employee):
def __init__(self,name,salary,area):
Employee.__init__(self,name,salary)
self.area=area
print("Constructor Developer")
def __del__(self):
Employee.__del__(self)
print("DeConstructor Developer ")
def PrintSelf(self):
Employee.PrintSelf(self)
print(self.area)
>>> d=Developer("bill",10000,"c")
Constructor Employee
Constructor Developer
>>> d.PrintSelf()
bill
10000
c
>>> del d
DeConstructor Employee
DeConstructor Developer
>>>
companyname="microsoft"
def printCompany():
print(companyname)
def __init__(self,name,salary):
self.name=name
self.salary=salary
print("Constructor Employee")
def __del__(self):
print("DeConstructor Employee")
def PrintSelf(self):
print(self.name)
print(self.salary)
>>> class Developer(Employee):
def __init__(self,name,salary,area):
Employee.__init__(self,name,salary)
self.area=area
print("Constructor Developer")
def __del__(self):
Employee.__del__(self)
print("DeConstructor Developer ")
def PrintSelf(self):
Employee.PrintSelf(self)
print(self.area)
>>> d=Developer("bill",10000,"c")
Constructor Employee
Constructor Developer
>>> d.PrintSelf()
bill
10000
c
>>> del d
DeConstructor Employee
DeConstructor Developer
>>>
注意:继承还有多继承和C++,C#的相似。