jingweimo的个人博客分享 http://blog.sciencenet.cn/u/jingweimo

博文

Class hierarchy and inheritance

已有 2009 次阅读 2017-7-10 05:05 |系统分类:科研笔记

class Particle (object):
   def __init__ (self, name='', position=(0.0,0.0,0.0),velocity=(0.0,0.0,0.0),
                 spin=0.0):
       self.position=position
       self.velocity=velocity
       self.name=name
       self.spin=spin
       
   def __str__ (self):
       print('in particle str')
       pos_str='({}:{}:{})'.format(self.position[0],self.position[1],self.position[2])
       vel_str='({}:{}:{})'.format(self.velocity[0],self.velocity[1],self.velocity[2])
       result_str='{} at {} with velocity {} and spin {}'.format(self.name,pos_str,vel_str,self.spin)
       return result_str


class MassParticle (Particle):
   def __init__(self, name='', position=(0.0,0.0,0.0),velocity=(0.0,0.0,0.0),
                 spin=0.0, mass=0.0):
       #we need to class the inherited method from the parent class
       Particle.__init__(self, name, position, velocity, spin) #bad codes
       self.mass=mass
   
   def __str__ (self):
       print('in mass str')
       result_str = Particle.__str__(self)
       result_str = result_str + ' and mass {}'.format(self.mass)
       return result_str

class ChargedParticle (MassParticle):
   def __init__ (self, name='', position=(0.0,0.0,0.0),velocity=(0.0,0.0,0.0),
                 spin=0.0, mass=0.0, charge=0.0):
       MassParticle.__init__(self, name, position, velocity, spin, mass) #bad code
       self.charge = charge
   
   def __str__(self):
       print('in charged str')
       result_str = MassParticle.__str__(self)
       result_str = result_str + ' and charge {}'.format(self.charge)
       return result_str
 

   

photon = Particle(name='photon', spin=1.0)  
print(photon)
tau = ChargedParticle(name='tau', spin=0.5, charge=-1.0, mass=1.77)  
print(tau)



https://blog.sciencenet.cn/blog-578676-1065468.html

上一篇:Tensorflow: ptw_word_lm.py implementation
下一篇:First test on diffuse optical tomography (DOT)
收藏 IP: 35.10.57.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-10-20 04:42

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部