# coding='utf-8'class User(): def __init__(self,name,sex): self.name = name self.sex = sex print '這裡是建構函式' def setName(self,name): self.name = name def getName(self): return self.nameuser = User("python",'男')user.setName("ruby")print user.getName()print user.nameprint user.sex#===========列印結果===============#這裡是建構函式#ruby#ruby#男
ruby的類定義
require 'jcode'$KCODE='u'class User attr_accessor :name,:sex def initialize(name,sex) @name = name @sex = sex p 'this is a constructor' end def get_name @name end def set_name(name) @name = name endenduser = User.new('Ruby','11')user.set_name('rubyruby')p user.get_namep user.namep user.sex
javascript的類定義
function User(name,sex){ this.name = name; this.sex = sex; alert("這裡是建構函式") } User.prototype ={ getName : function(){ return this.name }, setName :function(name){ this.name = name } } var user = new User("XXX",'man') user.setName("YYY"); alert(user.name) alert(user.sex)
# -*- coding:utf-8 -*-# 這是一個簡單的類,用於輸出一個精確到小數點後兩位的浮點數class RoundFloatManual(object): def __init__(self,val): assert isinstance(val,float),\ "Value must be a float" self.value = round(val,2) def __str__(self): return '%.2f' % self.valuerfm = RoundFloatManual(4.288)print rfm
# -*- coding:utf-8 -*-class Time60(object): '用於小時與分鐘的加減法運算' def __init__(self, hr=0, min=0): self.hr = hr self.min = min def __str__(self): return '%d:%d' % (self.hr, self.min) __repr__ = __str__ def __add__(self, other): a = divmod(self.min + other.min, 60) return self.__class__(self.hr + other.hr + a[0], a[1]) def __iadd__(self, other): a = divmod(self.min + other.min, 60) self.hr += self.hr + other.hr self.min += a[1] return selfa = Time60(10,30)b = Time60(8,45)print a+b
# -*- coding:utf-8 -*-
class NumStr(object):
def __init(self, num=0, string=''):
self.__num = num
self.__string = string
def __str__(self):
return '[%d::%r]' % \
(self.__num, self.__string)
__repr__ = __str__
def __add__(self, other):
if(isinstance(other, NumStr)):
return self.__class__(self.__num + other.__num, self.__string + self.__string)
else:
raise TypeError, '類型錯誤'
def __mul__(self, num):
if(isinstance(num, int)):
return self.__class__(self.__num * num, self.__string * num)
else:
raise TypeError, '類型錯誤'
def __nonzero__(self):
return self.__num or len(self.__string)
def __norm_cval(self,cmpres):
return cmp(cmpres,0)
def __cmp__(self,other):
return self.__norm_cval(cmp(self.__num,other.__num))+\
self.__norm_cval(cmp(self.__string,other.__string))