Ruby's Louvre

每天学习一点点算法

导航

python学习笔记——类

# 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.name
user = User("python",'男')
user.setName("ruby")
print user.getName()
print user.name
print 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
  end

end

user = User.new('Ruby','11')
user.set_name('rubyruby')
p user.get_name
p user.name
p 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.value
rfm = 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 self

a = 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))

posted on 2011-06-28 20:18  司徒正美  阅读(1357)  评论(0编辑  收藏  举报