Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

1.8. Class

class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'

x = MyClass()
    

1.8.1. __init__ 构造方法

def __init__(self):
    self.data = []
        
>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
        

1.8.2. print class

测试代码,当我们使用 print 打印一个 class

		
class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

t = Test(1234, 5678)
print(t)
		
		

输出

		
<__main__.Test object at 0x000002BA71D254F0>		
		
		

print 会调用 __str__() 和 __repr__() 方法,我们只需定义他们即可

		
class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "Test a:% s b:% s" % (self.a, self.b)

    def __str__(self):
        return "Test: a is % s, " \
               "b is % s" % (self.a, self.b)

    # Driver Code


t = Test(1234, 5678)

# This calls __str__()  
print(t)

# This calls __repr__()  
print([t]) 		
		
		

1.8.3. inner class(内嵌类)

		

#!/usr/bin/env python3
 
import os, sys
 
class parent:
	def __init__(self):
		self.name = 'parent'
 
	def getName(self):
		print(self.name)

	class child:
		def __init__(self):
			self.name = 'child'
 
		def getName(self):
			print(self.name)
		def getParentName(self):
			print(parent.name)
 
if __name__ == '__main__':
	child =  parent.child()
	child.getName()

	p = parent()
	p.getName()
	c =  p.child()
	c.getName()
	c.getParentName()		
		
		

1.8.3.1. 内嵌 Class 继承

			
class Geometry:
    class Curve:
        def __init__(self,c=1):
            self.c = c                          #curvature parameter
            print ('Curvature %g'%self.c)
            pass                                #some codes

    class Line(Curve):
        def __init__(self):
            Geometry.Curve.__init__(self,0)     #the key point
            pass                                #some codes

g = Geometry()
C = g.Curve(0.5)
L = g.Line()			
			
			

1.8.4. Python 枚举 Enum

		
from enum import Enum
class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7
		
		

1.8.4.1. auto()

		
from enum import auto
class Weekday(Flag):
    MONDAY = auto()
    TUESDAY = auto()
    WEDNESDAY = auto()
    THURSDAY = auto()
    FRIDAY = auto()
    SATURDAY = auto()
    SUNDAY = auto()
    WEEKEND = SATURDAY | SUNDAY
		
			
			
from enum import Enum, auto


class Color(Enum):
    RED = auto()
    BLUE = auto()
    GREEN = auto()


print(list(Color))
			
			
			

自定义 auto() 生成规则

			
from enum import Enum, auto


class AutoName(Enum):
    def _generate_next_value_(name, start, count, last_values):
        return name


class Ordinal(AutoName):
    NORTH = auto()
    SOUTH = auto()
    EAST = auto()
    WEST = auto()


print(list(Ordinal))
			
			
			

1.8.4.2. 枚举访问

			
from enum import Enum

class Weekday(Enum):
    monday = 1
    tuesday = 2
    wednesday = 3
    thirsday = 4
    friday = 5
    saturday = 6
    sunday = 7


print(Weekday.wednesday)
print(Weekday['wednesday'])
			
			
			
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color(1))
print(Color(2))
print(Color(3))

print(Color['RED'])
print(Color['GREEN'])
print(Color['BLUE'])
						
			
			

1.8.4.3. name 和 value

			
from enum import Enum
class Weekday(Enum):
    monday = 1
    tuesday = 2
    wednesday = 3
    thirsday = 4
    friday = 5
    saturday = 6
    sunday = 7
 
print(Weekday.wednesday)         # Weekday.wednesday      
print(type(Weekday.wednesday))   # <enum 'Weekday'>
print(Weekday.wednesday.name)    # wednesday
print(Weekday.wednesday.value)   # 3
			
			
			

1.8.4.4. 增加属性

			
from enum import Enum
class Weekday(Enum):
    monday = 1
    tuesday = 2
    wednesday = 3
    thirsday = 4
    friday = 5
    saturday = 6
    sunday = 7
 
Weekday.wednesday.label = "定时"
Weekday.wednesday.time = 10
 
print(Weekday.wednesday.label)   # 定时
print(Weekday.wednesday.time)    # 10
			
			
			

1.8.4.5. 唯一约束

正常情况,枚举允许重复出现相同的值

			
from enum import Enum
class Weekday(Enum):
    monday = 1
    tuesday = 2
    wednesday = 3
    thirsday = 4
    friday = 5
    saturday = 6
    sunday = 7
    test = 3
 
 
print(Weekday.test.value)    # 3
			
			

如果不希望出现重复,可以使用 @unique 注解

			
from enum import Enum, unique

@unique
class Weekday(Enum):
    monday = 1
    tuesday = 2
    wednesday = 3
    thirsday = 4
    friday = 5
    saturday = 6
    sunday = 7
    test = 3

try:
    print(Weekday.test.value)
except Exception as e:
    print(e)
			
			

运行会抛出异常

			
ValueError: duplicate values found in <enum 'Weekday'>: test -> wednesday			
			
			

1.8.4.6. 枚举比较

			
from enum import Enum
class Weekday(Enum):
    monday = 1
    tuesday = 2
    wednesday = 3
    thirsday = 4
    friday = 5
    saturday = 6
    sunday = 7
 
obj1 = Weekday.wednesday
 
obj2 = Weekday['wednesday']
 
obj3 = Weekday(3)
 
print(obj1==obj2==obj3)      # True
 
print(obj1 is obj2 is obj3)  # True
			
			
			

1.8.4.7. 遍历 enum 成员

			
from enum import Enum

class Shape(Enum):
    SQUARE = 2
    DIAMOND = 1
    CIRCLE = 3
    ALIAS_FOR_SQUARE = 2

for shape in Shape:
    print(shape.name, shape.value)			
			
			

输出结果

			
SQUARE 2
DIAMOND 1
CIRCLE 3			
			
			
			
from enum import Enum


class Shape(Enum):
    SQUARE = 2
    DIAMOND = 1
    CIRCLE = 3
    ALIAS_FOR_SQUARE = 2


for name, member in Shape.__members__.items():
    print(name, member)
			
			
			

输出结果

			
SQUARE Shape.SQUARE
DIAMOND Shape.DIAMOND
CIRCLE Shape.CIRCLE
ALIAS_FOR_SQUARE Shape.SQUARE			
			
			

1.8.4.8. IntEnum 整数值枚举

			
from enum import IntEnum


class Shape(IntEnum):
    CIRCLE = 1
    SQUARE = 2


class Request(IntEnum):
    POST = 1
    GET = 2


print(Shape == 1)
print(Shape.CIRCLE == 1)
print(Shape.CIRCLE == Request.POST)