【问题标题】:OOP - Python - How to call function within class and avoid the error of missing arguments caused by self?OOP - Python - 如何在类内调用函数,避免self导致的参数丢失错误?
【发布时间】:2021-01-01 03:09:43
【问题描述】:

我是 OOP 实践的初学者。

我想创建一个class 来执行我对数据库的查询。

这是我的代码:

class tools():
    def connect_db(self):
        cfg = ConfigParser()
        cfg.read('env.ini')
        sv_info = cfg['sv_info']

        db =  psycopg2.connect(
            host = db_connect['host'],
            user = db_connect['user'],
            password = db_connect['password'],
            database = db_connect['database'],
            port = db_connect['port']
        )
        return db


    def run_query(self, query):
        connection = self.connect_db
        do_the_query = connection.cursor()
        do_the_query.execute(query)
        do_the_query.fetchall()
        return do_the_query

    def find_locations(self,simple_query, latitude, longitude):
        return self.run_query(simple_query).format(latitude = latitude, longitude = longitude))

简单查询:

simple_query = """select * from a_function('{latitude}' , '{lontitude}')"""

我运行它的代码:

tools.find_locations(simple_query , '12.123456', '21.654321')

但是,我一直收到以下错误:

TypeError: find_locations() 缺少 1 个必需的位置参数: '经度'

根据我的研究,不应该考虑self 的论点(被忽略)。

无论如何,如果你们能更正我的代码就好了。

【问题讨论】:

    标签: python oop design-patterns


    【解决方案1】:

    注1

    我认为主要问题是您还不了解“”和“类的实例

    注 2 - 什么是类?

    一个“”代表一个复杂的事物,比如一个人。

    类的“成员变量”记录了关于更复杂的“”的简短事实

    名字JobApplicant 类的良好成员变量的示例。

    JobApplicant 的其他成员变量示例如下:

    • 求职者的姓氏
    • 求职者的年龄
    • 申请人的电话号码
    • 求职者的电子邮件地址。
    • 等等...

    课堂就像一张填空表,记录了一些小事实。

    假设有人正在为人们买卖房屋的网站编写代码。

    该程序员可能会编写一个名为 House 的类,它存储有关待售房屋的统计信息:

    class House:
        * number of bedrooms 
        * number of bathrooms
        * square footage of the house    
        * asking price to buy the house     
        * mailing address/location of the house
        * etc...      
    

    一个类的成员变量通常是事物(不是动作),例如:

    • 质量
    • 速度
    • 颜色
    • 温度

    类“方法”是用于操作成员变量的函数。 方法是动作,例如:

    • change_first_name
    • change_phone_number
    • 删除
    • 插入
    • 旋转
    • 反映
    • 翻译
    • 放大
    • 收缩
    • 游泳(动词,不是名词)
    • 跑(动词)
    • 跳过

    注意 3 “类”和“实例”之间的区别是什么?

    以下是一些词汇:

    • 类的实例
    • 类对象
    • 对象

    以上所有术语的含义相同。

    EXAMPLE CLASS INSTANCE NOTES
    JobApplicant class A JobApplicant class is like a paper job-application form which has not been filled-out yet. The JobApplicant class says that every JobApplicant has a "first name." Tthere is a blank line for a JobApplicant's pfirst name, but it has NOT been filled in yet. A class usually does NOT specify what a person's first name actually is. An instance of a class is like a job application will all of the information filled-out. An instance of a JobApplicant class might say first name = "Sarah". Not all instances have the same first nam e A class specifies what is the same for all instances. All "People" have a first name (inside of the computer... maybe not in real-life). Different instances can have different first names (Robby, Evelyn). Although the details might different, every instances of the Person class does have a first name, phone number, etc....
    blue-print of a house Architects draw blue-prints of houses. A *class is like a blue-print of a house. an instance of a House class is like an actual house made out of wood, and cement, steel screws, etc... An instance is NOT like a blue-print or drawing. Many different houses can all be built from the same blue-print. Many different instances all come from the same class

    注意 4 - python 中的self 参数

    下面是一些创建类实例的代码:

    
    class Cow:
        def moo(self, x = None, y = None, z = None):     
            print("M0o0o0o0o0o0o0oOoOoOoOoOoOoOoooooooooo...")
    # end of Cow class
    
    # the line below creates a new Cow named `robby`
    robby = Cow()      
    
    • Rectangle 是一个
    • robbyCow 的“instance
      instance 也称为 >对象

    以下两行代码是等价的:

    x = robby.moo(1, 2, 3)
    x = Cow.moo(robby, 1, 2, 3)
    

    如果您从类的实例调用方法,python 中的self 参数会自动为您填充。

    如果您从 本身调用方法,python 中的 self 参数 *** NOT *** 会自动为您填写。 p>

    实例和类彼此不同。

    self 应该是Cow 类的一个实例。

    理想情况下,python 会抱怨您向Cow.mooself 参数输入的任何内容,这不是牛。

    然而,python 允许奇怪的事情。 python 解释器允许您将狗、猫或任何其他动物传递给Cow.mooself 参数

    class Cow:
        def moo(self, x = None, y = None, z = None):
            print(type(self))
    # end of Cow class
    
    class Dog:
        pass
    
    class Cat:
        pass
    
    robby = Cow()
    fido = Dog()
    abby_the_alley_cat = Cat()
    
    Cow.moo(robby)
    Cow.moo(fido)
    Cow.moo(abby_the_alley_cat)
    Cow.moo(3.1459)
    Cow.moo("WHERE ART THOU ROMEO? WHERE ARE YOU MY DEAR?")  
    

    控制台输出如下所示:

    <class '__main__.Cow'>
    <class '__main__.Dog'>
    <class '__main__.Cat'>
    <class 'float'>
    <class 'str'>
    

    我认为您正在尝试编写所谓的“单例类

    如果你想要没有self参数的方法,我建议使用谷歌搜索类似“python初学者的解释静态方法” 也可以对“python类方法”做一些研究

    注意 [last_note_number + 1]

    下面是一些额外的代码供您使用:

    import io
    
    class BLAH(Exception):
        pass
    
    class Cow:
        def __init__(self, *args, **kwargs):
            # `__init__` get called every single time
            # that a new cow is instantiated from the Cow class
            #
            # Every time that a new cow comes into existence
            # the `__init__()` method is used
            #
            # I have written this function (__init__)
            # to ignore most of its input arguments.
            #
            # I recommend that you focus more on
            # understanding the difference between a class
            # and an instance of the class
            pass
    
        def moo(*args, **kwargs):
            # NOTE THAT:
            #     self ==args[0]
            #
            # EXAMPLE :
            #    CODE OUTSIDE OF CLASS:
            #        a = sally.moo(1, "blah", 3)
            #    INSIDE OF CLASS:
            #        args[0] == sally
            #        args[1] == 1
            #        args[2] == "blah"
            #        args[3] == 3
            output = ""
            try:
                args[0].my_static_method(*args, **kwargs)
                return output
            except AttributeError as exc:
                # `self` parameter is probably not
                # an instance of the Cow class.
                return str(exc)
    
        @staticmethod
        def my_static_method(*args, **kwargs):
            # The following code is confusing to read, but
            # focus more on the following two things:
            #
            #    * focus on the in-code comments describing
            #      what code does
            #
            #    * focus on what happens when you use/run the code
            #
            # The following code constructs a string.
            # The string contains the function inputs
            # We put each function-input on a different line
            #
            lamby = lambda arg: str(type(arg)).ljust(20) + repr(str(arg))
            middle = "\n".join(map(lamby, args))
            beginy = "WE ARE INSIDE OF " + "moo"
            endy = "WE ARE LEAVING " + "moo"
            output = io.StringIO()
            print(
                beginy,
                middle,
                endy,
                sep="\n",
                file=output
            )
            return output.getvalue()
    
    
        @classmethod
        def my_class_method(*args, **kwargs):
            out = ""
            try:
                out = args[0].my_static_method(*args, **kwargs)
                return out
            except BLAH:
                pass
    
    
    robby = Cow(width=3, length=11)
    
    # * `Cow` is a class
    # * `robby` is an "***instance of the class***"
    # `robby` is also known as an class ***object***
    # instances and classes are different from each-other.
    
    robby.moo(1, 2, 3)
    Cow.moo(robby, 1, 2, 3)
    
    simple_query = """select * from a_function('{latitude}' , '{lontitude}')"""
    result = Cow.moo(simple_query , 12.123456, 21.654321)
    print(result)
    
    result = robby.moo(simple_query , 12.123456, 21.654321)
    print(result)
    

    【讨论】:

      【解决方案2】:

      首先用 Class 定义对象。例如,我们使用 tools() 类创建一个名为“my_tools”的对象。

      my_tools = tools()
      

      一旦创建了对象,我们就可以在类中调用方法了。

      my_tools.find_locations(simple_query , '12.123456', '21.654321')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        • 2020-01-26
        • 1970-01-01
        • 1970-01-01
        • 2023-02-20
        • 2021-08-27
        • 2015-03-06
        相关资源
        最近更新 更多