首页 > 其他 > 详细

5类和对象-----类方法、静态方法

时间:2020-04-07 21:28:54      阅读:68      评论:0      收藏:0      [点我收藏+]

1、普通方法:绑定到对象,没有任何装饰,自动将对象(self)传给函数

2、类方法:用@classmethod装饰的方法,自动将类(cls)作为第一个参数传给函数,对象也可以调用

3、静态方法:用@staticmethod装饰的方法,不会自动传self或cls,就是一个普通的函数,类和对象都可以调用

#
HOST=127.0.0.1
PORT=3306
DB_PATH=rC:\Users\Administrator\PycharmProjects\test\面向对象编程\test1\db

class Mysql:
    def __init__(self, host, port):
        self.host = host
        self.port = port
    @classmethod
    def from_conf(cls):
        print(cls)
        return cls(HOST, PORT) #从配置文件中进行初始化
    def fun(self):
        print(self.fun(), self)
    @staticmethod
    def fun_static():
        print(form fun_static...)

print(Mysql.from_conf())
print(--------)
conn = Mysql.from_conf()
conn.from_conf()# 对象也可以调用,但默认传的第一个参数仍然是类,正常情况下不要乱去调用
print(--------)
m = Mysql(HOST, PORT)
Mysql.fun(m)
print(--------)
print(m.fun_static())

 

5类和对象-----类方法、静态方法

原文:https://www.cnblogs.com/cc-world/p/12649741.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!