1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Cat:
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def printInfo(self):
        print(self.name)
        print(self.age)
 
 
if __name__ == "__main__":
    from animal.wild import Tiger
    t = Tiger(10)
    t.showInfo()
cs

 

먼저 animal이라는 package에 pet이라는 모듈에 Cat 클래스가 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
# 다른 개발자가 만든 고양이
# from animal.pet import Cat
 
import animal.pet as ap
 
# 내가 만든 고양이
class Cat:
    def bite(self):
        print("꽉")
        
 
= ap.Cat("후추"5# 가까운 걸로 연결됨 -> 내가만든 Cat
c.printInfo()
cs

 

A모듈에서 Cat을 불러오려고 할때 만약 A모듈에서 같은 이름의 클래스를 생성하게 된다면

Cat이 생성되는 곳에서부터 가까운 Cat으로 연결이 된다.

이 경우 animal.pet의 Cat을 불러오고 싶다면

import animal.pet as ap 이름을 지정해준 다음

c = ap.Cat("후추", 5)로 불러와주면 된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Tiger:
 
    def __init__(self, weight):
        self.weight = weight
    
    def showInfo(self):
        print(self.weight)    
 
# if __name__ == "__main__":
#     이 모듈을 실행했을때
#     import때에는 실행 되지 않음
#     실질적인 Java의 main()의 역할
if __name__ == "__main__":
    from animal.pet import Cat
    c = Cat("후추"5)
    c.printInfo()
cs

 

pet 모듈에서 wild 모듈을 import,

wild 모듈에서 pet 모듈을 import  

각 모듈에서 서로를 import 할 경우 무한 루프가 돌면서 에러가 발생한다.

이를 막기 위해 Java에서 main의 역할을 하는  

if __name__ == "__main__":

안으로 pet모듈을 import 해줌으로써 무한루프 되는 것을 막을 수 있다.

 

 

'Python' 카테고리의 다른 글

15. Python - 다중상속  (0) 2021.02.23
14. Python - 상속, overriding  (0) 2021.02.23
12. Python - import_1  (0) 2021.02.23
11. Python - 생성자, 소멸자  (0) 2021.02.23
10. Python - OOP (객체지향)  (0) 2021.02.23

BELATED ARTICLES

more