iguanabanana iguanabanana - 3 months ago 12
Python Question

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. 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?

wim wim
Answer
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.

Therefore no changes to Parent.url will be reflected in calls to the random_method, because the soup is already collected.