更改子类中的父变量,然后在父类中使用新值?

时间:2016-08-18 22:36:46

标签: python

我正在处理python,目前我正在尝试使用子类方法更改Parent类变量的值。我的代码的基本示例如下。

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)

如果我运行方法,输出如下。

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

有人可以解释为什么我在运行print_url时可以获得新的url打印,但是如果我尝试在另一种方法中使用它,它会恢复为旧值吗?

2 个答案:

答案 0 :(得分:0)

因为当你使用Parent.url时,它使用类Parent中设置的静态值,而不是类实例中的值。

答案 1 :(得分:0)

class Parent(object):
    url = "http://www.google.com"
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "lxml")
    print(url)

分配soup的代码在类定义时运行一次。

因此,对Parent.url的调用不会反映random_method的更改,因为已经收集了汤。

相关问题