问题描述
我很难理解什么时候使用实例方法和静态方法更有意义.另外,我不知道我的函数是否是静态的,因为没有 @staticmethod 装饰器.当我调用其中一种方法时,我是否能够访问类函数?
I am struggling to understand when it makes sense to use an instance method versus a static method. Also, I don't know if my functions are static since there is not a @staticmethod decorator. Would I be able to access the class functions when I make a call to one of the methods?
我正在开发一个将信息发送到数据库的网络爬虫.它设置为每周运行一次.我的代码结构如下
I am working on a webscraper that sends information to a database. It’s setup to run once a week. The structure of my code looks like this
import libraries...
class Get:
def build_url(url_paramater1, url_parameter2, request_date):
return url_with_parameters
def web_data(request_date, url_parameter1, url_parameter2): #no use of self
# using parameters pull the variables to look up in the database
for a in db_info:
url = build_url(a, url_parameter2, request_date)
x = requests.Session().get(url, proxies).json()
#save data to the database
return None
#same type of function for pulling the web data from the database and parsing it
if __name__ == ‘__main__’:
Get.web_data(request_date, url_parameter1, url_parameter2)
Parse.web_data(get_date, parameter) #to illustrate the second part of the scrapper
这是基本结构.代码是功能性的,但我不知道我是否正确使用了这些方法(函数?),并且可能会错过将来使用我的代码的方法.我什至可能正在编写糟糕的代码,这些代码会导致错误,这些错误很难调试,只是因为我没有遵循最佳实践.
That is the basic structure. The code is functional but I don’t know if I am using the methods (functions?) correctly and potentially missing out on ways to use my code in the future. I may even be writing bad code that will cause errors down the line that are impossibly hard to debug only because I didn’t follow best practices.
在阅读有关何时使用类和实例方法之后.我不明白为什么我会使用它们.如果我想要构建 url 或从网站提取数据,我会调用 build_url 或 get_web_data 函数.我不需要函数的实例来单独跟踪任何东西.我无法想象什么时候我需要将一些我认为是问题的一部分的东西分开.
After reading about when class and instance methods are used. I cannot see why I would use them. If I want the url built or the data pulled from the website I call the build_url or get_web_data function. I don’t need an instance of the function to keep track of anything separate. I cannot imagine when I would need to keep something separate either which I think is part of the problem.
我认为我的问题与之前的问题不同的原因是:当我坐下来编写代码时,解释差异的概念性示例似乎对我没有帮助.我还没有遇到过使用不同方法解决的现实问题,这些方法显示了我什至应该何时使用实例方法,但在查看代码的概念示例时,实例方法似乎是强制性的.
The reason I think my question is different than the previous questions is: the conceptual examples to explain the differences don't seem to help me when I am sitting down and writing code. I have not run into real world problems that are solved with the different methods that show when I should even use an instance method, yet instance methods seem to be mandatory when looking at conceptual examples of code.
谢谢!
推荐答案
您在代码中编写的函数是实例方法,但它们编写不正确.实例方法必须将self
作为第一个参数
The functions you have wrote in your code are instance methods but they were written incorrectly.An instance method must have self
as first parameter
即def build_url(self, url_paramater1, url_parameter2, request_date):
那你就这么称呼它
get_inst = Get()
get_inst.build_url(url_paramater1, url_parameter2, request_date)
这个 self
参数是由 python 提供的,它允许您访问 Get
类的所有属性和函数 - 无论是静态的还是非静态的.
This self
parameter is provided by python and it allow you to access all properties and functions - static or not - of your Get
class.
如果您不需要访问类中的其他函数或属性,则添加 @staticmethod
装饰器并删除 self
参数
If you don't need to access other functions or properties in your class then you add @staticmethod
decorator and remove self
parameter
@staticmethod
def build_url(url_paramater1, url_parameter2, request_date):
然后就可以直接调用了
Get.build_url(url_paramater1, url_parameter2, request_date)
或从类实例调用
get_inst = Get()
get_inst.build_url(url_paramater1, url_parameter2, request_date)
但是您可能会问您当前的代码有什么问题?尝试从这样的实例调用它,你会看到问题
But what is the problem with your current code you might ask?Try calling it from an instance like this and u will see the problem
get_inst = Get()
get_inst.build_url(url_paramater1, url_parameter2, request_date)
创建实例有用的示例:假设您想制作一个聊天客户端.
Example where creating an instance is useful:Let's say you want to make a chat client.
你可以这样写代码
class Chat:
def send(server_url, message):
connection = connect(server_url)
connection.write(message)
connection.close()
def read(server_url):
connection = connect(server_url)
message = connection.read()
connection.close()
return message
但是有一个更干净、更好的方法:
But a much cleaner and better way to do it:
class Chat:
def __init__(server_url):
# Initialize connection only once when instance is created
self.connection = connect(server_url)
def __del__()
# Close connection only once when instance is deleted
self.connection.close()
def send(self, message):
self.connection.write(message)
def read(self):
return self.connection.read()
要使用你做的最后一堂课
To use that last class you do
# Create new instance and pass server_url as argument
chat = Chat("http://example.com/chat")
chat.send("Hello")
chat.read()
# deleting chat causes __del__ function to be called and connection be closed
delete chat
这篇关于Python 何时使用实例与静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!