[英]Change a parent variable in subclass, then use new value in parent class?
I'm just getting to grips with python, and am currently trying to change the value of a Parent class variable using a subclass method. 我刚开始接触python,目前正在尝试使用子类方法更改Parent类变量的值。 A basic example of my code is below.
我的代码的基本示例如下。
from bs4 import BeautifulSoup
import requests
import urllib.request as req
class Parent(object):
url = "http://www.google.com"
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
print(url)
def random_method(self):
print(Parent.soup.find_all())
class Child(Parent):
def set_url(self):
new_url = input("Please enter a URL: ")
request = req.Request(new_url)
response = req.urlopen(request)
Parent.url = new_url
def print_url(self):
print(Parent.url)
If I run the methods, the outputs are as follows. 如果运行这些方法,则输出如下。
run = Child()
run.Parent()
>>> www.google.com
run.set_url()
>>> Please enter a url: www.thisismynewurl.com
run.print_url()
>>> www.thisismynewurl.com
run.random_method()
>>> #Prints output for www.google.com
Can anyone explain why I can get the new url printing when I run print_url, but if I try and use it in another method, it reverts to the old value? 谁能解释为什么我在运行print_url时可以获得新的url打印,但是如果我尝试在另一种方法中使用它,则会恢复为旧值?
因为当您使用Parent.url
它将使用在Parent类中设置的静态值,而不是来自该类实例的值。
class Parent(object):
url = "http://www.google.com"
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
print(url)
The code to assign the soup
is run once, at time of class definition . 在类定义时,分配
soup
的代码运行一次。
Therefore no changes to Parent.url
will be reflected in calls to the random_method
, because the soup is already collected. 因此,对
Parent.url
更改不会反映在对random_method
调用中,因为汤已被收集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.