class People:
say='hello'
def __init__(self,name,sex):
self.name=name
self.sex=sex
def print_name(self):
if self.name=='':
print('请添加姓名')
else:
print(self.name)
if __name__=='__main__':
people1=People('lisa','woman')
people2=People('','man')
people1.print_name()
people2.print_name()
print(people1.say)
print(People.say)
people1.say='你好'
print(people1.say)
print(People.say)
del people1.say
print(people1.say)
>>>lisa
>>>请添加姓名
>>>hello
>>>hello
>>>你好
>>>hello
>>>hello
一、类的内置方法 命名的时候在前后加入两个下划线:__init__ 1、__init__ 生成对象时,系统默认执行,使实例从一开始就拥有类模板所具有的属性 2、__str__ 二、私有化 1、成员私有化,self.__name='lisa' ,属性名前加两个下划线,禁止在外部访问
class People:
say='hello'
def __init__(self):
self.__name='lisa'
self.sex='woman'
def print_name(self):
if self.name=='':
print('请添加姓名')
else:
print(self.name)
if __name__=='__main__':
people1=People()
people1.__name
>>>Traceback (most recent call last):
File "F:/pycharm project/data_processing/python_/class_.py", line 37, in <module>
people1.__name
AttributeError: 'People' object has no attribute '__name'
2、方法私有化,def __print_name(self)' ,方法名前加两个下划线,禁止在外部访问
class People:
say='hello'
def __init__(self):
self.name='lisa'
self.sex='woman'
def __print_name(self):
if self.name=='':
print('请添加姓名')
else:
print(self.name)
if __name__=='__main__':
people1=People()
people1.__print_name()
>>>Traceback (most recent call last):
File "F:/pycharm project/data_processing/python_/class_.py", line 37, in <module>
people1.__print_name
AttributeError: 'People' object has no attribute '__print_name'
三、类的继承 1、
class People:
say='hello'
def __init__(self,name,sex):
self.name=name
self.sex=sex
def print_name(self):
if self.name=='':
print('请添加姓名')
else:
print(self.name)
class Student(People):
pass
if __name__=='__main__':
people1=Student('lisa','woman')
print(people1.name,people1.sex)
people1.print_name()
>>>lisa woman
>>>lisa
2、子类中创建与父类同名的方法(重写父类方法)
class People:
say='hello'
def __init__(self,name,sex):
self.name=name
self.sex=sex
def print_name(self):
if self.name=='':
print('请添加姓名')
else:
print(self.name)
class Student(People):
def print_name(self):
if self.name=='':
print('please add name')
else:
print('the people name is:',self.name)
if __name__=='__main__':
people1=Student('lisa','woman')
people1.print_name()
>>>the people name is: lisa
|