Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

1.7. Class

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

x = MyClass()
    

1.7.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.7.2. 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.7.2.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()