Creating a Python class class

I got acquainted with the concept, first of all, watching the excellent Raymond Hettinger video and reading the accepted answer here , and I am wondering that I was wrong.

class ReadHTML(object):

    def __init__(self, url):
        page = urlopen(url).read()
        self.page = page

    @classmethod
    def from_file(cls, path):
        page = open(path).read()
        return cls(page)

It works

r = ReadHTML('http://example.com')
print r.page

and it is not

r = ReadHTML.from_file('example.html')
print r.page 

it gives me an error, as if I was trying to "twist" the file:

File "/usr/lib/python2.7/urllib2.py", line 258, in get_type
    raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: <!doctype html>

Do you see what is wrong?

+4
source share
3 answers

You still call the class initializer ReadHTML.__init__()when you call cls(page); this call is no different from the call ReadHTML(page), you just use a different link. This method accepts only a parameter url, and the code passes this value urlopen()independently.

ReadHTML.__init__(), URL-:

class ReadHTML(object):
    def __init__(self, url=None, page=None):
        if url is not None:
            page = urlopen(url).read()
        self.page = page

    @classmethod
    def from_file(cls, path):
        page = open(path).read()
        return cls(page=page)

.

+5

from_file , __init__(), , ReadHTML.from_file('example.html'), :

page = urlopen(open('example.html').read()).read()

Martijn , :

class ReadHTML(object):
    def __init__(self, url, opener=urlopen):
        self.page = opener(url).read()

    @classmethod
    def from_file(cls, path):
        return cls(path, opener=open)

, (, , ).

+2

, . , , URL-.

, .

class ReadHTML(object):

    def __init__(self, page):
        self.page = page

    @classmethod
    def from_filename(cls, path):
        with open(path) as f:
            page = f.read()
        return cls(page)

    @classmethod
    def from_url(cls, url):
        page = urlopen(url).read()
        return cls(page)

As a side note, I consider the urllib / urllib2: // support file, so you don't really need a file name constructor (but I still think it's good).

+1
source

Source: https://habr.com/ru/post/1529011/


All Articles