python基礎—面向對象


感覺和java相比一個是大公司,一個是小公司, 大公司規範有文檔,小公司簡約效率高


面向對象  
# 成員屬性名稱前 加上 __ 意爲private
# get / set :  get_name()   set_name(name) 
class Student:
	def __init__(self, name, age):
		self.name = name
		self.age = age
		
	def detail(self):
		print(self.name)
		print(self.age)
      
class PrimaryStudent(Student):  # inherent
	def lol(self):
		print('can not win then run faster than others')

class CollegeStudent(Student):
	def __init__(self, name, age, gf):  # overrite構造函數
		self.name = name
		self.age = age
		self.gf = gf

	def gf_detail(self):
		print(self.gf)

obj1 = PrimaryStudent('小學生', 7)
obj1.lol()
obj1.detail()

obj2 = CollegeStudent('王思聰', 29, '張雨欣')
obj2.detail()
obj2.gf_detail()

print(dir(obj1))                            # class info as list
print(hasattr(obj1, 'name'))        # True
setattr(obj1, 'name', 'jack')  
print(getattr(obj1, 'name'))          # jack
print(getattr(obj1, 'name', 404))  # jack
fn = getattr(obj1, 'detail')             #7
fn()

#  實例屬性和類屬性
class Student(object):
	name = 'Student'
	def __init__(self, name):
		self.name = name   # 類屬性
s = Student('Bob')
s.score = 90			   # 實例屬性

print(s.name) 
s.name = 'Jack'          # 給實例屬性綁定name屬性, 實例屬性優先級比類屬性高 
print(s.name)              # Jack
print(Student.name)   # Student
del s.name                 # 刪除實例name屬性
print(s.name)             # Student


I'm fish, I'm on.


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