inflearn logo
강의

Khóa học

Chia sẻ kiến thức

Từ cơ bản đến nâng cao Python do kỹ sư Silicon Valley giảng dạy

Tìm hiểu về metaclass (Metaclasses) dùng để tạo ra các class từ class

(메타클래스) 해당 강의 코드 혹시 올려주실 수 있을까요?

Đã giải quyết

421

enopus

3 câu hỏi đã được viết

1

질문은 많으시면 많을수록 좋습니다. 가능한 빠른 답변 드리겠습니다.

원활한 답변을 위해, 자세한 질문 사항 부탁드려요

 

열심히 타이핑해서 저장을 해뒀는데 실수로 삭제를 해버렸네요. 복습 겸 다시 듣고 있는데 혹시 다른 강의처럼 코드를 올려주실 수 있을까요?

python 알고리즘

Câu trả lời 3

1

altoformula

안녕하세요 서영민님,

제가 레플릿 설정을 보니 모든 강의가 공개로 되어있었네요. 필요하시다면 https://replit.com/@SeungjoonLee4에서 모든 코드 접근하셔서 복사하시면 될 듯 합니다.

1

altoformula

안녕하세요 서영민님,

코드 밑에 복사해뒀습니다. 타 강의와는 달리 강의들이 Replit에 있어서 공유하기가 힘든 면이 있는데, 시간을 내서 Github으로 옮겨보도록 하겠습니다. 의견 감사드립니다!

# Metaclasses are just classes that create other classes
# Classes are essentially just building blocks of code that tell you how to produce an object. We can then instantiate each object to create unique instances of that class.


# class Car(object):

#     def __init__(self, brand, color):
#         self.brand = brand
#         self.color = color

#     def __repr__(self):  # special method
#         return f"Brand: {self.brand}, Color: {self.color}"


# myTesla = Car("Tesla", "White")
# # print(myTesla)
# # Brand: Tesla, Color: White

# # Python
# # instances of the classes is consdered objects, but also class is considered object

# myTesla = Car("Tesla", "White")
# print(type(myTesla))
# # <type 'instance'>
# print(type(Car))
# # <type 'classobj'>

# # dynamically created Class
# EVCar = type('Car', (), {})
# print(EVCar())

# # # # # Name — Name of the class
# # # # # Bases — Any Classes we inherit from
# # # # # Attrs — Any Attributes associated with the same class.
# # # # # type(name, bases, attrs)

# # Create Basic Class of Car
# class Car(object):

#     def __init__(self, brand, color):
#         self.brand = brand
#         self.color = color

#     def __repr__(self):
#         return f"Brand: {self.brand}, Color: {self.color}"

# # Create additional method for our new Class
# def charge(self):
#     return "Charging up"

# # Create Class EVCar, inheriting from Car class with an extra attribute (batter_cap) and method (charge)
# EVCar = type('EVCar', (Car, ), {"batter_cap": "75KW", "charge": charge})
# print(EVCar)

# # Create Instance of EVCar called 'lucid'
# myLucid = EVCar('Lucid', 'Yellow')

# print(myLucid.brand)
# print(myLucid.color)
# print(myLucid.charge())

# # We can leverage type to dynamically create our other classes.
# class Meta(type):
#     # __new__ is a magic method that gets called before __init__ that determines how the class is constructed.
#     def __new__(self, name, bases, attrs):
#         return type(name, bases, attrs)

# Car = Meta('Car', (), {})
# print(Car)

class Car(object):

    def __init__(self, brand, color):
        self.brand = brand
        self.color = color

    def __repr__(self):
        return f"Brand: {self.brand}, Color: {self.color}"

# Create our Metclass
class Meta(type):
    def __new__(self, name, attrs):
        attrs['shape'] = 'sendan'

        # Return the Class and automatically inherit from Car.
        return type(name, (Car, ), attrs)

# Create the EVCar class
EVCar = Meta('EVCar', {})

# # Create Instance of EVCar class
lucid = EVCar('Lucid', 'Yellow')

print(lucid)

print(lucid.shape)

0

enopus

빠른 답변 정말 감사드립니다!

주피터 설치되어있는지 어디서 확인해요 도대체

0

139

4

pandas 설치 안되요 짜증나요

0

151

3

명령프롬포트에 파이썬 설치 안되요

0

124

3

윈도우에서 VScode 사용 시 질문입니다.

0

83

2

첨부파일이 열리지 않습니다.. .pdf.json 파일로 받아지네요ㅠ

0

106

2

Replit 강의 자료가 안나와요

0

106

3

Replit UI 변경으로 인한 실습 진행 문의

1

97

1

replit에서 developer frameworks가 안보여요

0

185

2

[업데이트] 파이썬 패키지 부분에서 안되어서 강의 진행 불가

2

189

3

html 읽기 오류

1

228

2

DataFrame groupby 사용관련 질문

1

208

2

pylint shell 사용법

0

138

2

자막오류 수정가능한가요?

0

135

1

복합 조건절 관련 궁금증

0

131

2

49.행맨 프로그램 - 재시도 횟수 관련.

1

132

1

64. 파이썬 입문자가 쉽게 빠지기 쉬운 몇가지 에러(혹은 로직)에 대해 알아보기

0

204

2

Replit UI가 업데이트 되서 강의 진행이 멈췄어요

2

265

3

Replit을 사용해보려고 하는데 영상처럼 진행이 안되네요

3

673

3

실무에서의 제네레이터 함수 사용에 관한 질문입니다.

0

133

2

영상이 소리만 나오고 영상은 안보입니다.

0

169

2

pandas 오류 질문

0

240

2

상속 질문

1

187

2

total을 float으로 바꾸신 이유

0

257

2

섹션2 ["환경 vs. 설정 vs. 구성"] 강의 자막 문의

0

189

1