第十六天学习:python的类(1)

使用关键字class创建类,class后面跟类名,可以自定义,最后以冒号结尾。
语法:
class Classname:
‘’‘类的说明’‘’
类的内容
 
类的内容可以写类的全局变量,类的方法等。
实例:
class ren(object):
    '''this is a new class'''
    name = 'meinv'
    sex = 'woman'
    def hello(self):
        print('hello world')

a = ren()
print(type(a))
print(a.name)
print(a.sex)
a.hello()
print('*************************')
a.name = 'meizi'
a.job = 'teacher'
print(a.job)
print(a.name)
print(dir(a))
结果:
<class '__main__.ren'>
meinv
woman
hello world
*************************
teacher
meizi
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'hello', 'name', 'sex']

 

解释:
1.object 默认是所有类的父类,不写默认继承object
2.a=ren() ,就是类ren 的实例化
3.调用类的变量和方法。使用‘.’来调用
4.如果想给实例a添加变量或赋值,可以使用‘.’ 加变量赋值就可。
 
 
__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法
self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self
self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类.:
class ren(object):
    def prt(self):
        print(self)
        print(self.__class__)

test = ren()
test.prt()
结果:
<__main__.ren object at 0x024EA270>
<class '__main__.ren'>


实例:
class ren(object):
    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
    def hello(self):
        print('hello {},sex is {}'.format(self.name, self.sex))

test = ren('xiaomei', 'f')
test.hello()
结果:
hello xiaomei,sex is f
有__init__方法。在创建实例的时候,不能传入空的参数,必须传入与__init__方法匹配的参数,但self不用传,解释器会把实例变量传入

 

面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。继承完全可以理解成类之间的类型和子类型关系
子类继承父类所有的属性和方法,还可以自定义子类的属性和方法
object是所有类的父类,所有的类默认继承object类,它是一个超级类,如果不写,默认继承object
格式:
class A(父类)
 
python支持多继承
class A:
......
class B:
......
class C(A, B)
......
 
类的继承注意:
(1).在继承中类的构造(__init__)不会自动调用,它需要在子类的构造中亲自调用
(2)python总是首先子类中的方法,如果子类中没有找到,才会去父类中查找
 
实例:
class parent(object):
    name = 'parent'
    sex = 'F'
    def __init__(self):
        print('my name is {}'.format(self.name))
    def get_name(self):
        return self.name
    def get_sex(self):
        return self.sex

class child(parent):
    name = 'child'
    sex = 'M'
    def __init__(self):
        print('my name is {}'.format(self.name))
    def hello(self):
        print('hello world')

a = child()
a.hello()
print(a.get_name())
print(a.get_sex())
结果:
my name is child
hello world
child
M

 

如果注释类child中sex变量# sex = 'M',打印出来的将是F

 

 

原文地址:https://www.cnblogs.com/yshan13/p/7796248.html