python面向对象的绑定方法、隐藏属性

时间:2021-07-13
本文章向大家介绍python面向对象的绑定方法、隐藏属性,主要包括python面向对象的绑定方法、隐藏属性使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

绑定方法

绑定方法分为两种:
     1.绑定给对象的
     2.绑定给类的
  
  绑定给对象的:
    class Student():
        country = 'CHINA'

        def __init__(self, name, age):
          self.name = name
          self.age = age

        def tell_info(self):
          print("%s-%s" % (self.name, self.age))

    obj = Student('egon',  30)
    obj.tell_info()

 绑定给类的:
  setting.py
   IP = '192.168.1.101'
   PORT = 3306
   import setting
   class Mysql():
      country = 'CHINA'

      def __init__(self, ip, port):
          self.ip = ip
          self.port = port

      def tell_info(self):
          print("%s-%s" % (self.ip, self.port))

      # 类方法是绑定给类的,类来调用, 把类名当做第一个参数传递
      @classmethod
      def from_config(cls):          
          obj = cls(settings.IP, settings.PORT)
          return obj

       obj=Mysql('127.0.0.1',80)
       obj.tell_info()
       obj1 = obj.from_config()
       print(obj1.country)
       Mysql.from_config()  # Mysql.from_config(Mysql)

非绑定方法

非绑定方法:不绑定给对象,也不绑定给类

  #随机产生一个字符串
    import uuid
    print(uuid.uuid4())
  
  调用方法参数该怎么传就怎么传
    class Mysql():
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port

        @staticmethod # 静态方法
        def create_id(x, y, z):
            import uuid
            print(uuid.uuid4())

    obj = Mysql('127.0.0.1',3306)
    obj.create_id(1,2,3)

    Mysql.create_id()
    def func():
      print(111)
    func(1,2,3)

隐藏属性

类定义阶段,只是语法上得变形
  该隐藏对外不对内, 如果想访问类中隐藏属性,在类中开放对外访问的接口,可以更好的对外部做限制
    变形操作只在类定义阶段, 之后的所有属性或者方法,都不会变形了
————下划线变量就是隐藏属性
    class People():
        __country = 'CHINA'  # _People__country
        def __init__(self, name, age):
            self.__name = name
            self.age = age
        def __func(self):  # _People__func
            print("func")

        def test(self):
             return self.__country # self._People__country

        def get_name(self):
            return "名字:%s" % self.__name

        def get_country(self):
             return "国家:%s" % self.__country

        def set_country(self, v):
             if type(v) is not str:
                 print("country必须是str类型")
                 return
             self.__country = v
        def del_country(self):
             print("不删除")
  obj = People('ly', 18)
  print(obj.get_country())
  print(obj.get_country())
  print(obj.name)
  print(obj.get_name())

  ps:Python3 中统一了类与类型的概念

原文地址:https://www.cnblogs.com/zty78/p/15006887.html