【博学谷学习记录】超强总结,用心分享丨人工智能 Python面向对象 学习总结之Python与Java的区别

前言

经过学习,对Python面向对象部分有了一定的了解。
总结记录:面向对象上Python与Java的部分区别

简述

从类、对象、特性三个层面来简述其部分区别
在这里插入图片描述

面向对象

Python Java
定义 class ClassName(object):pass public class ClassName{}
类名要与文件名一致
属性 在类中,方法外定义属性即可 需要使用static修饰
方法 使用@classmethod修饰
第一个形参一般为cls
需要使用static修饰
权限控制(类和对象中使用方式相同) 通过属性或方法名控制
公有 public = ‘public’
私有 __private = ‘private’(两个下划线开头)
通过关键字控制
public,protected,default,private

python中还有静态函数,@staticmethod修饰,静态函数与类函数的区别是,静态函数不在形参中的得到类本身,一般用于逻辑上属于类,但并不需要进行类中属性和方法的操作

class ClassName(object):
    public = 'public'
    __private = 'private'

    @classmethod
    def class_method(cls):
        print(cls.__private)

    @staticmethod
    def static():
        print("Class Test")
public class ClassName {
    public static final String STR = "String";

    protected static void classMethod() {

    }

    private static String classMethod1() {
        return "";
    }

}

对象

Python Java
创建 Object() new Object()
属性 __init__(self)方法中定义 需要显示定义
方法 就是函数的写法,第一个形参为self代表对象本身
转字符串方法为__str__(self)
权限修饰符、返回值、方法名组成。this关键字代表对象本身
转字符串方法为toString()

特性

Python Java
封装 - -
继承 在类的参数列表中声明基类
多继承(需注意mro)
通过extends关键字声明父类
单继承
多态 - -

MRO(Method Resolution Order):方法解析顺序,我们可以通过类名.__mro__或类名.mro()获得“类的层次结构”,方法解析顺序也是按照这个“类的层次结构”寻找。

class Father(object):
    def __init__(self, name):
        self.name = name
        self.car = 5

    def father_active(self):
        return self.name + "工地工作"


class Mother(object):
    def __init__(self, name):
        self.name = name
        self.house = 2

    def mother_active(self):
        return self.name + "厂子工作"


class Son(Father, Mother):
    def __init__(self, name):
        super().__init__(name)
        Mother.__init__(self, name)


f = Father("爸爸")
m = Mother('妈妈')
s = Son("儿子")
print(s.father_active())
print(s.mother_active())
print(f"儿子有{s.car}辆车")
print(f"儿子有{s.house}套房")
public class Father {
    private String name;
    protected int car = 5;

    public Father(String name) {
        this.name = name;
    }
    protected String fatherActive(Father father) {
        return father.name + "工地工作";
    }

}

// ----------------next file--------------------- 
  
public class Son extends Father{

    public Son(String name) {
        super(name);
    }
    public static void main(String[] args) {
        Son son = new Son("儿子");

        System.out.println(son.fatherActive(son));
        System.out.println("儿子有" + son.car + "辆车");
    }
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>