I am trying to learn Python. This is a really simple code. All I am trying to do here is to call a class\'s constructor. Initialize some variables there and print that varia
You should possibly make data
a keyword parameter with a default value of empty dictionary:
class DHT:
def __init__(self, data=dict()):
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
If error is like Author=models.ForeignKey(User, related_names='blog_posts') TypeError:init() missing 1 required positional argument:'on_delete'
Then the solution will be like, you have to add one argument Author=models.ForeignKey(User, related_names='blog_posts', on_delete=models.DO_NOTHING)
You're receiving this error because you did not pass a data
variable to the DHT constructor.
aIKid and Alexander's answers are nice but it wont work because you still have to initialize self.data
in the class constructor like this:
class DHT:
def __init__(self, data=None):
if data is None:
data = {}
else:
self.data = data
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
And then calling the method showData like this:
DHT().showData()
Or like this:
DHT({'six':6,'seven':'7'}).showData()
or like this:
# Build the class first
dht = DHT({'six':6,'seven':'7'})
# The call whatever method you want (In our case only 1 method available)
dht.showData()
You need to pass some data into it. An empty dictionary, for example.
if __name__ == '__main__': DHT('a').showData()
However, in your example a parameter is not even needed. You can declare it by just:
def __init__(self):
Maybe you mean to set it from the data?
class DHT:
def __init__(self, data):
self.data['one'] = data['one']
self.data['two'] = data['two']
self.data['three'] = data['three']
def showData(self):
print(self.data)
if __name__ == '__main__': DHT({'one':2, 'two':4, 'three':5}).showData()
showData
will print the data you just entered.
Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:
class DHT:
def __init__(self):
self.data = {}
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
Or even just:
class DHT:
def __init__(self):
self.data = {'one': '1', 'two': '2', 'three': '3'}
def showData(self):
print(self.data)
The problem is with, you
def __init__(self, data):
when you create object from DHT class you should pass parameter the data should be dict type, like
data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)
But in your code youshould to change is
data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()
Or
if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()