python語法31[類]
一 最簡單的類
>>> 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
>>>
注意:
python與C#一樣,為純面向對象語言,所有的類都有共同的基類object。
python的內置類型都有對應的class對應,例如整形對應的類為int,字符串對應的類為str等。
類的定義使用關鍵字class,類名后面()為基類的名字。
>>> 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
>>>
>>> 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
>>> 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
>>> 注意:繼承還有多繼承和C++,C#的相似。


浙公網安備 33010602011771號