Python和java的类比较

Python 类的定义

1. 初步比较

class people:
	# 成员变量 类似java 中的public标识符
	name = ' '
	age = ' '
	#  私有成员变量,类似java中的private标识符
	__weight = 0
	
	# 定义构造方法,类似javaz中的构造方法
	# 这里的self 类似java中的 this,实际就是该实例的地址
	# self.__class__ 是指向类
	def __init__(self,n,a,w):
		self.name = n
		self.age = a
		self.__weight = w
		
	# 定义共有方法
	def speak(self):
		print("%s 说: 我 %d 岁"%(self.name,self.age))
	
	# 定义私有方法
	def __foo(self):  
        print('这是私有方法')

# 实例化类
p = people('limm',10,30)
p.speak()
p.foo() # 异常

2. 继承

class student(people):
	grade = ' '
	def __init__(self,n,a,w,g):
		#类似于super()
		people.__init__(self,n,a,w,)
		self.grade = g
	
	# 覆写父类方法
	def speak(self)
		print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
		

3. 多继承


class people:
    name = ' '
    age = ' '
    __weight = 0

    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("%s 说: 我 %d 岁。" % (self.name, self.age))


class student(people):
    grade = ''

    def __init__(self,n,a,w,g):
        people.__init__(self, n, a, w)
        self.grade = g

    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))


class speaker():
    topic = ''
    name = ''

    def __init__(self, n, t):
        self.name = n
        self.topic = t

    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s" % (self.name, self.topic))

class sample(speaker,student):
    a = ''
    def __init__(self,n,a,w,g,t):
        student.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)

test = sample("Tim",25,80,4,"Python")
test.speak()   #方法名同,默认调用的是在括号中排前地父类的方法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章