python - When to use __init__ when creating a class -
after using django while, got use using classes without def __init__(self): ...
when declaring variables. used declare variables in __init__
function, realize there cases don't need to, i'm unclear on when use or not. seems there problem when trying pass class variable, should use init in these cases?
i know use __init__
cases, makes short classes cleaner without it, know when can , cannot use it.
example:
class basescraper(object): # whithout __init__, passing site() site wont work. # site = site() # parser = none def __init__(self): self.site = site() self.parser = none class site(object): # no trouble declaring url str url = "" def set(self, url): self.url = url def get(self): return self.url if __name__ == "__main__": scraper = basescraper() scraper.site.set('http://www.google.com') print scraper.site.get()
attributes declared in class owned class rather individual instances of class. in site
example, url
no more property of individual site objects set
or get
are. kind of example, want instance data - can initialize in __init__
.
python: difference between class , instance attributes has discussion of differences.
Comments
Post a Comment