Python面向对象

来源:互联网 发布:js禁用button按钮 编辑:程序博客网 时间:2024/06/12 01:51

通过学习Java我们就知道类有属性和方法。
还有一个特殊的方法叫做构造方法
test.py下定义类

class Employee():    classstr='this is a test'    def __init__(self,name,pay):        self.name=name        self.pay=pay        print('name',name)    def hello(self):        print(self.name)

一个.py文件就是一个模块就想是Java中的jar.
我们可以通过一下三种方式获取调用test.py下面的类。

import testtest.Employee('liusen',12000).hello()

输出结果

name liusenliusen

第二种方法

from test import EmployeeEmployee('liusen',12000)

输出结果:

name liusen

第三种方法

from test import *Employee('liusen',12000)

实验结果:

name liusen

(1)这里可以看到init在实例化类的时候直接被调用。
(2)classstr和self.name变量的区别
(3)python有没有private和protect
(4)Python类是不是继承object类
(5)object类中有什么属性?
(6)Python中有没有接口
(7)Python怎么调用父类的构造方法?
(8)python中的类方法和静态方法是怎么定义的?
(9)python有没有接口?
(10)Python是否存在重载和重写?
(11)析构函数del跟Java中的析构函数的区别?
(12)object类有什么方法?
第二个问题:
以classstr和name为例,classstr是类的属性而name是实例化对象的变量。
实验代码:

from test import *employee=Employee('liusen',12000)print(employee.classstr)print(Employee.classstr)print(employee.name)print(Employee.name)

实验结果:

name liusenthis is a testthis is a testliusenTraceback (most recent call last):  File "/home/ubuntu/PycharmProjects/pythonproject/object/class.py", line 7, in <module>    print(Employee.name)AttributeError: type object 'Employee' has no attribute 'name'

从上面可以看出name只是实例化变量employee的变量,而classstr不仅是实例化变量employee的变量也Employee的变量。
第三个问题
Python中没有严格意义上面的private和protect虽然用__在变量的左边修饰。但是我们也是可以访问的到的。

class Employee():    classstr='this is a test'    __name='liyanmeng'    def __init__(self,name,pay):        self.name=name        self.pay=pay        print('name',name)    def hello(self):        print(self.name)

调用对象:

from test import *employee=Employee('liusen',12000)print(employee._Employee__name)print(employee.__name)

实验结果:

/usr/bin/python3.4 /home/ubuntu/PycharmProjects/pythonproject/object/class.pyname liusenliyanmengTraceback (most recent call last):  File "/home/ubuntu/PycharmProjects/pythonproject/object/class.py", line 5, in <module>    print(employee.__name)AttributeError: 'Employee' object has no attribute '__name'

虽然不能直接访问,但是还是可以通过添加对象名进行访问。
第六个问题:
python 没有抽象类、接口的概念
第七个问题:
见如下网址

http://blog.csdn.net/tianlihua306/article/details/28046609

定义静态方法:

class Employee():    classstr='this is a test'    __name='liyanmeng'    def __init__(self,name,pay):        self.name=name        self.pay=pay        print('name',name)    def hello(self):        print(self.name)    @staticmethod    def static():        print("static function")

实验结果

name liusenliyanmengstatic functionTraceback (most recent call last):  File "/home/ubuntu/PycharmProjects/pythonproject/object/class.py", line 6, in <module>    Employee.hello()TypeError: hello() missing 1 required positional argument: 'self'
原创粉丝点击