First of all, excuse my ignorance if this is a fairly easy question. What I would like to achieve is to create an attribute for every instance of the class (i.e. filepath
), change it for an instance (i.e. in the first case, where I change the value of filepath
for the a
instance, but if I create a new instance, e.g. b
I would like to keep the original filepath
value.
filepath = '/path/to/original/file'
class A(object):
@classmethod
def _set_path(cls, filepath):
cls.filepath = filepath
return cls.filepath
def __init__(self, name):
self.name = name
A._set_path(filepath) # Set filepath for all instances: /path/to/original/file
a = A("Alice")
print(a.filepath)
a._set_path("/path/to/another/file") # Set filepath for instance a, but the way I've written the code the filepath value will be the new one
# for every new instance.
print(a.filepath)
b = A("Bob")
print(b.filepath) # I would like to keep /path/to/original/file
Is there a way to improve this code and/or have a smart design pattern for this case?
Aucun commentaire:
Enregistrer un commentaire