class Student : #定义一个类
myname = 'xiaohong'
__age__ = 18;
def __init__(self,sex): # 构造函数,初始化数据
self.sex = sex
def hello(self):#self 类本身
print('Student hello')
def say(self,name):
print('hi ,%s' %name) # %s是占位符 %name 是方法传进来的参数 相当于局部变量
print('i am '+ self.myname +', is ' + self.sex) # %self 相当于全局变量
print('i am %s , is %s , age %i' %(self.myname, self.sex,self.__age__))
def setage(self,age):
self.__age__ = age;
s = Student('nan')#创建对象使用括号
s.myname = 'asd'; #公共变量 可以修改
print('age:' + str(s.__age__)) # 私有变量 只能访问 不能修改
s.hello()
s.setage(19)
s.say('xiaohua')
print('*' * 8 )
class People (Student): #继承 继承具有传递性
def hello(self): #子类覆盖父类的方法
print(' i am people')
p = People('nan') # 父类的init 带有参数,子类创建的时候也需要带参数,也就是说默认继承父类的构造方法
print( '使用父类的myname:' + p.myname)
p.setage(15) # 使用父的方法
p.say('xiaoming')
print( " hasattr(p,'myname') 是否有myname : "+ str(hasattr(p,'myname')))
setattr(p,'addr','python') # 设置属性
print(hasattr(p,'addr'))
print(p.addr)
a = getattr(p,'addr')
print(a)
这是输出
age:18
Student hello
hi ,xiaohua
i am asd, is nan
i am asd , is nan , age 19
********
使用父类的myname:xiaohong
hi ,xiaoming
i am xiaohong, is nan
i am xiaohong , is nan , age 15
hasattr(p,'myname') 是否有myname : True
True
python
python