Одна конкретная переменная c не определена. Не знаю почему. - PullRequest
1 голос
/ 20 июня 2020

enter image description here

I'm working on a python Project which is, to be shor a social study based on a database from pplapi. My first study is about the link between the age of a person an her wealth.From a dictionary, I pick up the information that gives me the age of the people and the one which gives me their wealth, then I put these information into a matrix and I plot everything. My second study is about the link between the happiness and the size of the city in which someone leaves. As before I pick up in the same dictionary the information that I need, I put everything into a matrix and I plot everything. I'm trying to do some object programming and I'm new to this.

The problem is in my class Zone, I defined a variable called "H" but python says that this variable is not defined. I suppose there is a trick with the "@classmethod" I put above my function but I don't know what to do to fix everything up. Can someone help me and if possible explain me what happens when I do this command? I added an image of the error message that Python gives me.

import json 
import math
class Agent: # Les class n'ont pas de () à la fin 

    def dire_bonjour(self,prenom):
        return "Bonjour {} !".format(prenom)
    def __init__(self,position,**agent_attributes):
        self.position = position 
        for attr_name, attr_value in agent_attributes.items():
            setattr(self,attr_name,attr_value)
class Position:
    def __init__(self, abscisses_degrees, ordonnees_degrees):
        self.abscisses_degrees = abscisses_degrees
        self.ordonnees_degrees = ordonnees_degrees
    @property
    def abscisses_rad(self):
        return self.abscisses_degrees * math.pi / 180 
    @property 
    def ordonnees_rad(self):
        return self.ordonnees_degrees * math.pi / 180
class Zone:
    ZONES = []
    MIN_LONGITUDE_DEGREE = -180
    MAX_LONGITUDE_DEGREE = 180
    MIN_LATITUDE_DEGREE = -90
    MAX_LATITUDE_DEGREE = 90
    DDEGREES = 1
    Η = 1

    def __init__(self, corner1,corner2):
        self.corner1  = corner1
        self.corner2 = corner2 
        self.inhabitants = 0
    @classmethod
    def initialize_zones(cls):
        for abscisses in range(cls.MIN_LATITUDE_DEGREE,cls.MAX_LATITUDE_DEGREE,H):
            for ordonnees in range(cls.MIN_LONGITUDE_DEGREE,cls.MAX_LONGITUDE_DEGREE,DDEGREES):
                bottom_left_corner = Position(longitude,latitude)
                top_right_corner = Position(longitude+cls.DDEGREES,latitude+H)
                zone = Zone(bottom_left_corner,top_left_corner) 
                cls.ZONES.append(zone)
        print(len(cls.ZONES))

def main():
    for agent_attributes in json.load(open("agents-100k.json")):
        abscisses = agent_attributes.pop("latitude")  #Latii est couchée....(latitude)
        ordonnees = agent_attributes.pop("longitude") # pour ne prélever que la valeur souhaitée, utiliser agent_attributes.pop(str)
        position = Position(abscisses,ordonnees)
        agent = Agent(position,**agent_attributes)
        Zone.initialize_zones()

To make things easier, I put here a git hub link where you can find the code I'm trying to reproduce, you can find also the data base that I'm using.
https://github.com/OpenClassrooms-Student-Center/la_poo_avec_python/tree/04_class_methods

Ответы [ 3 ]

0 голосов
/ 20 июня 2020

Поскольку вы украшаете его как метод класса (@classmethod), вам нужно получить доступ к нему как к переменной класса cls.H.

Может быть, приведенный ниже небольшой пример немного поможет вам

class base_foo:

    cls_variable = "I'm in Class...."
    @staticmethod
    def say_static_hello():
        print("Hello...")

    @classmethod
    def say_class_hello(cls):
        if(cls.__name__=="class_foo"):
            print(cls.cls_variable)
            print("Hello foo")
        elif(cls.__name__=="class_bar"):
            print(cls.cls_variable)
            print("Hello bar")

class class_foo(base_foo):
    def say_class_hello(self):
        print("Class foo")

class class_bar(base_foo):
    def say_static_hello(self):
        print("Class bar")


test_foo = class_foo()
test_foo.say_class_hello()
test_foo.say_static_hello() 

test_bar = class_bar()
test_bar.say_class_hello()
test_bar.say_static_hello()

Вывод:

Class foo
Hello...
I'm in Class....
Hello bar
Class bar

РЕДАКТИРОВАТЬ:

Что-то не так, поэтому я изменил код, чтобы его не выполнить с файлом ниже. отдельный файл?

Почему?

В вашем файле есть Diacritics (Non-Ascii) :) вот почему. Проверьте это https://pteo.paranoiaworks.mobi/diacriticsremover/

import math
class Agent: # Les class n'ont pas de () à la fin 

    def dire_bonjour(self,prenom):
         return "Bonjour {} !".format(prenom)
    def __init__(self,position,**agent_attributes):
         self.position = position 
         for attr_name, attr_value in agent_attributes.items():
              setattr(self,attr_name,attr_value)
class Position:
    def __init__(self, abscisses_degrees, ordonnees_degrees):
         self.abscisses_degrees = abscisses_degrees
         self.ordonnees_degrees = ordonnees_degrees
    @property
    def abscisses_rad(self):
         return self.abscisses_degrees * math.pi / 180 
    @property 
    def ordonnees_rad(self):
         return self.ordonnees_degrees * math.pi / 180
class Zone:
    ZONES = []
    MIN_LONGITUDE_DEGREE = -180
    MAX_LONGITUDE_DEGREE = 180
    MIN_LATITUDE_DEGREE = -90
    MAX_LATITUDE_DEGREE = 90
    DDEGREES = 1
    H = 1

    def __init__(self, corner1,corner2):
         self.corner1  = corner1
         self.corner2 = corner2 
         self.inhabitants = 0
    @classmethod
    def initialize_zones(cls):
         for abscisses in range(cls.MIN_LATITUDE_DEGREE,cls.MAX_LATITUDE_DEGREE,cls.H):
              for ordonnees in range(cls.MIN_LONGITUDE_DEGREE,cls.MAX_LONGITUDE_DEGREE,DDEGREES):
                    bottom_left_corner = Position(longitude,latitude)
                    top_right_corner = Position(longitude+cls.DDEGREES,latitude+cls.H)
                    zone = Zone(bottom_left_corner,top_left_corner) 
                    cls.ZONES.append(zone)
         print(len(cls.ZONES))

def main():
    for agent_attributes in json.load(open("agents-100k.json")):
         abscisses = agent_attributes.pop("latitude")  #Latii est couchée....(latitude)
         ordonnees = agent_attributes.pop("longitude") # pour ne prélever que la valeur souhaitée, utiliser agent_attributes.pop(str)
         position = Position(abscisses,ordonnees)
         agent = Agent(position,**agent_attributes)
         Zone.initialize_zones()
0 голосов
/ 21 июня 2020

Вот мой код только с символами ascii, я не вижу, где должна произойти разница ... Я везде добавил "cls" перед буквой H, но у меня все еще та же проблема. Есть ли что-нибудь, что python изменили создатели, что могло бы объяснить мою проблему?

import json
class Agent: # Les class n'ont pas de () a la fin 

    def dire_bonjour(self,prenom):
         return "Bonjour {} !".format(prenom)
    def __init__(self,position,**agent_attributes):
         self.position = position 
         for attr_name, attr_value in agent_attributes.items():
              setattr(self,attr_name,attr_value)
class Position:
    def __init__(self, abscisses_degrees, ordonnees_degrees):
         self.abscisses_degrees = abscisses_degrees
         self.ordonnees_degrees = ordonnees_degrees
    @property
    def abscisses_rad(self):
         return self.abscisses_degrees * math.pi / 180 
    @property 
    def ordonnees_rad(self):
         return self.ordonnees_degrees * math.pi / 180
class Zone:
    ZONES = []
    MIN_LONGITUDE_DEGREE = -180
    MAX_LONGITUDE_DEGREE = 180
    MIN_LATITUDE_DEGREE = -90
    MAX_LATITUDE_DEGREE = 90
    DDEGREES = 1
    H = 1

    def __init__(self, corner1,corner2):
         self.corner1  = corner1
         self.corner2 = corner2 
         self.inhabitants = 0
    @classmethod
    def initialize_zones(cls):
         for abscisses in range(cls.MIN_LATITUDE_DEGREE,cls.MAX_LATITUDE_DEGREE,cls.H):
              for ordonnees in range(cls.MIN_LONGITUDE_DEGREE,cls.MAX_LONGITUDE_DEGREE,DDEGREES):
                    bottom_left_corner = Position(longitude,latitude)
                    top_right_corner = Position(longitude+cls.DDEGREES,latitude+cls.H)
                    zone = Zone(bottom_left_corner,top_left_corner) 
                    cls.ZONES.append(zone)
         print(len(cls.ZONES))

def main():
    for agent_attributes in json.load(open("agents-100k.json")):
         abscisses = agent_attributes.pop("latitude")  #Latii est couchee....(latitude)
         ordonnees = agent_attributes.pop("longitude") # pour ne prelever que la valeur souhaitee, utiliser agent_attributes.pop(str)
         position = Position(abscisses,ordonnees)
         agent = Agent(position,**agent_attributes)
         Zone.initialize_zones()```
 
0 голосов
/ 20 июня 2020

Вы определили H внутри класса и должны ссылаться на него как self.H. У вас также есть методы класса, которые необходимо объявить как принимающие self в качестве первого параметра.

...