Arguments specified during initialization do not respond well

Asked 2 years ago, Updated 2 years ago, 192 views

I have a question in the program below.When generating an instance, the following error occurs even though the argument is 7005670031 」:

 "NameError: name 'zipcode' is not defined"

When an Address class initializer receives an argument, it recognizes it as a zipcode, and then the next function specifies it as a zipcode, but this error occurs.

[Additional questions]
print(f"Address: {address['zipcode']} {address['address1']} {address['address2']} {address['address3']}}")

Why should I write "f" with this code?

import requests
import json

# zip code acquisition
Class Address:

    def__init__(self, zipcode):
    
        self.zipcode = zipcode

    default_address(self):
        url="https://zipcloud.ibsnet.co.jp/api/search"
        param={"zipcode":zipcode}

        res=requests.get(url,params=params)
       # print(res.text)
        
        results=response ["results" ]
        address=results[0]#Some things may return more than one
        print(f "Address: {address['zipcode']} {address['address1']} {address['address2']} {address['address3']}")  

add=Address ("5670031")
result=add.get_address()

print(result)

python

2022-09-30 21:53

1 Answers

The code below is not particularly meaningful, but for clarity, let's shorten the code as follows:

class Address:
    def__init__(self, zipcode):
        self.zipcode = zipcode

    default_address(self):
        param={"zipcode":zipcode}

add=Address ("5670031")
result=add.get_address()

print(result)

NameError: name 'zipcode' is not defined

The error appears.Now, let's fix it so that there are no errors.

class Address:
    def__init__(self, zipcode):
        self.zipcode = zipcode

    default_address(self):
        param={"zipcode":self.zipcode}

add=Address ("5670031")
result=add.get_address()

print(result)

Have you noticed what the difference is?zipcode in the get_address method has been replaced with self.zipcode.Access the properties through self..

zipcode appears all over the code with the same name, but be aware of the scope and Python's own writing rules, think about which zipcode you want to access now and code it.

In other words,

When the Address class initializer receives an argument, it recognizes it as a zipcode, and then the next function specifies it as a zipcode

This recognition is wrong.The scope of the initializer argument zipcode is only within the initializer.I'm substituting self.zipcode=zipcode and properties to see the value I received from other methods.Object orientation may be unfamiliar at first, but I think it would be good if you get used to it.


2022-09-30 21:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.